Godot 3 - Rotation doesn't effect axis for velocity

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By bobokox
:warning: Old Version Published before Godot 3 was released.

Hey!

I have a question about rotation in Godot 3.0.
I want to make a simple movement script, but the velocity always forces in the same direction, no matter where i rotate the node. neither rotation nor global_rotate works.

here is my script:

if Input.is_action_pressed("ui_up"):
	linear_velocity = Vector3(-5,0,0)
if Input.is_action_pressed("ui_down"):
	linear_velocity = Vector3(5,0,0)
if Input.is_action_pressed("ui_left"):
	rotation += Vector3(0,0.1,0)
if Input.is_action_pressed("ui_right"):
	#rotation -= Vector3(0,0.1,0)
	global_rotate(Vector3(0,1,0), deg2rad(1))

What type of node is this script on? How are you applying the velocity to the node?

literalcitrus | 2018-01-24 23:54

it’s a rigid body. what do you mean with applying? this is not a variable, linear_velocity does the same like set_linear_velocity in godot 2.

bobokox | 2018-01-25 01:28

Okay, I have a inclination that linear_velocity uses global axis for translation. Probably the easiest way to recalculate the linear velocity is to use some matrix math to convert the local movement into it’s corresponding global movement.

I’ve only briefly tested this:

var local_velocity
if Input.is_action_pressed("ui_up"):
    local_velocity= Vector3(-5,0,0)
if Input.is_action_pressed("ui_down"):
    local_velocity= Vector3(5,0,0)
if Input.is_action_pressed("ui_left"):
    rotation += Vector3(0,0.1,0)
if Input.is_action_pressed("ui_right"):
    #rotation -= Vector3(0,0.1,0)
    global_rotate(Vector3(0,1,0), deg2rad(1))

linear_velocity = global_transform.basis.orthonormalized().xform(local_velocity)

The important stuff is in the last line. It’s basically taking the matrix that defines the rotation (and scale) of the RigidBody, orthonormalizes it (removing the scale) and then multiplies it by the input vector, essentially “rotating” the input vector.

literalcitrus | 2018-01-25 02:14

thank you very much! this helps a lot.
i modified it like this:

linear_velocity = global_transform.basis.orthonormalized().xform(linear_velocity)

and did after each if query, where the velocity is applied.

thank you for the help!

bobokox | 2018-01-25 10:41