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)
Moving In A Direction
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.
- Edited
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)
@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.
- Edited
Do you mean the rotate() method of a Spatial node? https://docs.godotengine.org/en/stable/classes/class_spatial.html#class-spatial-method-rotate
I think the first argument would be Vector3(1, 0, 0) for the X-axis, Vector3(0, 1, 0) for the Y-axis, and Vector3(0, 0, 1) for the Z-axis. You could also use the constants here, e.g. Vector3.UP: https://docs.godotengine.org/en/stable/classes/class_vector3.html#constants