How to use (3D) KinematicBody's "move_and_slide" to move the object forward?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By bastilo

Hey, I’m still learning 3D…

So I rotate the Player object (which is a 3D KinematicBody) and then I want to move it forward to the direction it was rotated. So I tried

move_and_slide(Vector3(0, 0, 1))

but that doesn’t work because it needs global coordinates instead of local coordinates, I guess. I read the tutorial on this several times and looked up some example codes but I don’t really get the idea of it. How do I move my object forward to the direction it is facing? Is there an easy and understandable explanation for this?

Thank you!

:bust_in_silhouette: Reply From: SIsilicon

You can use the 3rd vector of the global transform of the object.

var facing = global_transform.basis.z
1 Like
:bust_in_silhouette: Reply From: eons

You can use: transform.basis.xform(motion_direction)*motion_speed
That will transform the motion vector to the local transform (remember that forward is -z on your meshes), is what you put on the move_and_slide parameter.

The platformer and kinematic demos have more examples of motions related to the camera.

1 Like
:bust_in_silhouette: Reply From: Markus Dick

I know this is kinda late, but since i was strugeling with the same problem and found no real answers online i thought i comment here:

The problem is that move _ and _ slide moves the kinematic body in the global transform, while the rotation is stored in its local transform.

Lets say your direction Vector is (through key presses for example):

var global_direction = Vector3(0,0,1)

and you don´t want to move in the global direction, but in the local direction the kinematic body is facing. First, you rotate the vector on the axis you want (in my example i rotate around the y-axis ( its the Vector3(0,1,0) )):

var local_direction = global_direction.rotated(Vector3(0,1,0), rotation.y)

rotation is a Vector3 that stores the current rotation of the kinematic body in radians and since i want to rotate around the y-axis i use its y value

Finally you can call move _ and _ slide(), in my example however i want to apply speed to the direction first:

var velocity = local_direction * SPEED

I hope this helps people, that want to achieve some first or third person movement and use a kinematic body as a player and move with the move _ and _ slide() method.

Oh boy. Thank you so much for this… I was tearing my hair out! I think I’ll make a PR to update the docs to mention that move_and_slide is not expecting local coordinates like Translate does…

Matthew Goulart | 2020-04-19 19:15

I love you… A lot.

sante | 2020-11-15 18:25

Finally, after spending hours scratching my head and looking for help everywhere without getting any. Thenks.
I must say, I laughed at myself for not thinking about something like that.

magicalogic | 2020-11-15 18:25

1 Like