Part 6: Handling inputs - krisp3t/KrisRaycaster GitHub Wiki

Handling inputs

We need a way for user to be able to move around the area. If you have a touchscreen, you can use touch events in TouchGFX - handleClickEvent, handleDragEvent and handleGestureEvent. We will only need the first two.

When the user starts dragging their finger across the screen, we should handle that action. A move horizontally should rotate the player and a move vertically should move the player forwards or backwards.

The moves are relative, that's why we need to keep previous touch position in memory.

Vec2 previousTouchPos = { 0, 0 };
PlayerDirection playerDir = PlayerDirection::STOPPED;

When user releases the finger, we will reset the previous touch position.

void GameScreenView::handleClickEvent(const ClickEvent& event)
{
    if (event.getType() == ClickEvent::RELEASED)
    {
        touchgfx_printf("Click event released\n");
	previousTouchPos = { 0, 0 };
        playerDir = PlayerDirection::STOPPED;
    }
}

Now we can handle the drag event and appropriately transform the player.

void GameScreenView::handleDragEvent(const DragEvent& event)
{
    Vec2 evt{ event.getNewX(), event.getNewY() };
    //touchgfx_printf("Drag event at (%d, %d)\n", evt.x, evt.y);
    TransformPlayer(evt);
}
void GameScreenView::TransformPlayer(Vec2 evt)
{
    if (previousTouchPos.x == 0 && previousTouchPos.y == 0)
    {
        previousTouchPos = evt;
        return;
    }
    Vec2f delta = { (evt.x - previousTouchPos.x) * 1.0f, (evt.y - previousTouchPos.y) * 1.0f };
    float length = sqrt(delta.x * delta.x + delta.y * delta.y);
    previousTouchPos = evt;

    constexpr float rotateSensitivity = 0.02f;
    Raycaster::rotatePlayer(delta.x * rotateSensitivity);
    playerDir = delta.y > 0 ? PlayerDirection::FORWARDS : PlayerDirection::BACKWARDS;
}

We can also implement deadzone so that the application will not react to very slight movements:

    if (length < 3.0f)
    {
        return;
    }
    if (abs(delta.y) > 3)
    {
        playerDir = delta.y > 0 ? PlayerDirection::FORWARDS : PlayerDirection::BACKWARDS;
    }

Resources