player moves left and right when i move diagonally

Godot Version

4.3

Question

When i move forward in between two axes, my character moves a little bit to the left or right as well as the direction i intend to go. Any ideas why this could be happening? I tried using lerp instead of move_toward but that movement was extremely static and unrealistic. I want to have the player move only in the intended, forward direction. Any help would be appreciated.

Here is the script:

func _physics_process(delta):

if not is_on_floor():

velocity.y -= gravity \* delta

var input_dir = Input.get_vector(“left”, “right”, “forward”, “backward”)

var direction = (head.transform.basis * Vector3(input_dir.x, 0, input_dir.y)).normalized()

if direction:

velocity.x = move\_toward(velocity.x, direction.x \* SPEED, 2) #starts movement smoothly, needs work

velocity.z = move\_toward(velocity.z, direction.z \* SPEED, 2)

else:

velocity.x = move\_toward(velocity.x, 0, 1) #stops movement smoothly

velocity.z = move\_toward(velocity.z, 0, 1)

move_and_slide()

I really can’t explain it well, so I let AI create text for my code:

Multiplying the axes (like head_right * input_dir.x and head_forward * input_dir.y) and adding them together is a common technique used to convert 2D input (typically from a player using a keyboard or joystick) into a 3D direction based on an object’s orientation.

var head_forward = head.transform.basis.z
var head_right = head.transform.basis.x
var direction = (head_right * input_dir.x) + (head_forward * input_dir.y)
direction.y = 0 # we don't want to move in the y axis, do this before normalizing it
direction.normalized() # normalize the vector to get consistent movement in all directions

This is also being used for directions when using a third person camera and you want to move relative to the camera.