I want an object to move in the direction it's facing, but I'm not sure how to do that. I used some code with sin() and cos() that worked before in a different engine, but it doesn't seem to be working here. How do you make something move in the direction it's pointing in Godot? (2D)

If you have the angle, then you can convert it to a Vector2 using the following:

var direction = Vector2(cos(global_rotation), sin(global_rotation))

And then the direction will point in the direction the Node2D is facing if forward for the Node2D at rotation 0 is facing upward, if I recall correctly. If forward at rotation 0 is in a different direction, then you'll need to apply an offset:

var angle_offset = deg2rad(90) # to make it face right
var direction = Vector2(cos(global_rotation + angle_offset), sin(global_rotation + angle_offset))

And by altering the offset you can make it where the direction faces in the same direction as the Node2D.

Here's some code I'm using for a RigidBody2D.

speed and dir are floats. dir is the direction in radians, in the range -PI to PI, measured clockwise from the positive X-axis. linear_velocity is a Vector2 property of a RigidBody2D.

	# Set velocity (speed and direction).
	# First set the velocity vector along the positive X-axis, using the specified speed.
	# Then rotate the velocity vector to the specified direction.
	linear_velocity = Vector2(speed, 0.0).rotated(dir)

a month later

@DaveTheCoder said: Here's some code I'm using for a RigidBody2D.

speed and dir are floats. dir is the direction in radians, in the range -PI to PI, measured clockwise from the positive X-axis. linear_velocity is a Vector2 property of a RigidBody2D.

	# Set velocity (speed and direction).
	# First set the velocity vector along the positive X-axis, using the specified speed.
	# Then rotate the velocity vector to the specified direction.
	linear_velocity = Vector2(speed, 0.0).rotated(dir)

I am trying to use the rotated() function in 3D, and it says to put an axis for argument 1, how would I signify I want to use the Y axis? The documentation doesn't really say.

10 months later