Detecting wether the player is moving in the direction its facing

Godot Version

4.2.2.stable.mono

Question

Hello everyone, I am wondering what the best way to detect which direction (relative to the player) the player is moving in.

For example, the player is facing some object. The player can move move toward the object, away from the object, and strafe around the object all while facing it. What I want to know is how can I tell if the player is moving forward (in the direction of -player.Transform.Basis.Z) or to its left/ right etc.

This seems like it has a simple solution but I’m having a hard time seeing it. I hope I asked this question clear enough so you can understand what I’m asking, if not please leave a reply and I’ll try and explain more.

Thanks!

Edit: I may have found the solution, if you keep track of your player direction based on input. For example

if(Input.IsActionPressed("Forward"))
{
    direction.z += 1
}

then you can compare that direction to the Basis of the object. You can say if the difference between the forward of an object (-Transform.Basis.Z) and the direction (as defined above) is zero (or near zero) then the object is moving in that direction. So

if (-Transform.Basis.Z - direction == Vector3.Zero)
{
    # the object is moving forward (relatively)
}

and

if(Transform.Basis.X - direction == Vector3.Zero)
{
    # the object is moving right (relatively)
}

If anyone has a cleaner way, or an interesting way to do this, or can see how this could be improved let me know!

You want the dot product. There’s a pretty good explanation of it in the docs here alongside an example that I think will help you solve your problem. Vector math — Godot Engine (stable) documentation in English

Bit of an Isla de Muerta - very hard to find if you don’t already know what it’s called!

3 Likes

Thank you for the reply, (what I described in my edits also works if anyone comes by with a similar problem later on). Isla de Muerta applies to so many things haha!

1 Like

Very true, especially when writing code! No problem.

1 Like

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.