(3D) Move player to direction of rotation

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

I have a character that moves relative to the camera (that can be rotated around player w/ mouse). Player can move 360° (and rotates to the direction it’s moving), no problem, BUT I want to change how this works.

I want to rotate the character with WASD and only apply speed to the Z-vector, so it will turn more smoothly (I think) and I could add, let’s say, an attack that moves the player to the direction it’s facing.

I guess I could make that work with what I already have but I dont know how to apply “force” to the direction player is going or was going.

I have looked around everywhere and tried everything. pls send help im losing it.

:bust_in_silhouette: Reply From: drawgy

Well, I got it…kinda working. While the attack animation is playing, player moves overtime to the facing direction. Multiplying with bigger numbers makes it move faster.

var angle = player.get_rotation().y   
velocity = Vector3(sin(angle),0, cos(angle)) * 10

there is a MUCH better way to do the same thing, here you are converting a vector into an angle and then back into a vector, which is very inefficient.

Simply use: velocity = player.global_transform.basis.z.normalized() * 10
(adjust with the direction your player is facing)

global_transform.basis.z is the blue arrow when you select your player in local coordinates. “normalized()” is only useful if your player is scaled.

Joel_127 | 2019-04-11 15:07

:bust_in_silhouette: Reply From: wombatstampede

You get the direction of the Z-Vector of any Spatial with: (This is a Vector3)
global_transform.basis.z
If you want to ignore the y-component of that Vector you could use:
Vector3(global_transform.basis.z.x,0,global_transform.basis.z.z)

I assume that you currently use a KinematicBody. If you really want to use Forces and Physics you could use a RigidBody instead. But I’m unsure if you really want that as it probably implies a completely different Behaviour of the “player”.
Anyway just to have it said, you would go like this to move the player forward (as a RigidBody):

var forward_force=10

_process(delta): #could also make sense inside integrate_forces
  #maybe you have to multiply the vector by -1 if forward and backward is changed
  apply_impulse(Vector3(0,0,0),global_transform.basis.z * forward_force * delta)