0
\$\begingroup\$

So far I've implemented horizontal (X-axis) and vertical (Z-axis) linear movement for the player in a 3D game. Using the code shown below, the player is able to move relative to the camera's Y-axis rotation.

rotationOffset represents the direction:

  • 0.f = Forward
  • 90.f = Right
  • 180.f = Backwards
  • -90.f = Left
velocity.x = glm::sin(cameraYRotation + rotationOffset) * speed;
velocity.z = glm::cos(cameraYRotation + rotationOffset) * speed;

I use key press & release events to set the velocity using the code above.

However, I'm not sure how I can implement diagonal movement, such as when the player is moving Forward + Right.

If the player is initially moving Forward, but then starts moving to the right as well to move diagonally, how would can I apply that change to the velocity?

Should I create more variables to keep track of the keys being pressed?

Furthermore, how do I deal with key releases (e.g. Player initially moves diagonally Forward + Right, but then releases the Right key, thus only moves Forward)?

\$\endgroup\$

1 Answer 1

0
\$\begingroup\$

I tend to develop in 2D, but your question seems more functional-based so I might be able to help, hopefully.

Maybe this approach is a little naïve, but perhaps try post-incrementing the movement of your player-character by an incremental amount when you change direction on the Keypress/D-Pad. This will smoothly move your player character in the scene, rather than snap them to one, set direction.

You'll need to make sure that you are applying the incremental change with every Update() as long as the Key-Press is being held. For Key-Releases, simply post-decrement the axis-value with every Update() until it reaches '0'. Blending 'Forward' and 'Right' movement should then result in "diagonal" movement more naturally.

So it might function like this pseudo code:

Vector3 movement;
double x;
double y;
double z;

public SomeConstructor()
{
    movement = new Vector3(x, y, z);
}

....

private void On_KeyPressUp()
{
    if (z < 1)
    z += 1;
}

private void On_KeyPressRight()
{
    if (x < 1)
    x += 0.1;
}

private void On_KeyReleaseUp()
{
    if (z > 0)
    z -= 0.1;
}

private void On_KeyReleaseRight()
{
    if (x > 0)
    x -= 0.1;
}


private void Update()
{
    MovePlayer(movement);
}

Also maybe look into 'Linear Interpolation'. It may help shed some light on helpful smoothing-techniques. Hope this may have helped.

Helpful Research: Game Engine Architecture By Jason Gregory · 2017 (p.181) https://www.google.co.uk/books/edition/Game_Engine_Architecture/LlLSBQAAQBAJ?hl=en&gbpv=0

\$\endgroup\$
0

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .