• Godot HelpProgramming
  • Anyway to set a different rotation anytime the character move a different direction?

So basically, what I want to try is when the character spawns, they are at the rotation of 0 degrees. When they move to the left or to the right, they move 90 and -90 degrees accordingly. I've tried this by creating a variable for left which is:

var left = rotation(insert number here)

This was so that I could use left when the button for moving left was pressed and let go.

func _physics_process(delta):
	if Input.is_action_just_pressed(input name for forward):
	var left = rotation(-90)
if Input.is_action_just_released(same thing)

Like I expected, it didn't work. I don't entirely know how rotation works in godot, or how to use it in code. Does anyone have any suggestions?

Is the game 2D or 3D?

For 2D, I would recommend setting the global_rotation property. The global_rotation property takes radians though, so you will need to convert it using deg2rad. Something like this should work:

func _physics_process(delta):
	if Input.is_action_just_pressed(input_name_here):
		global_rotation = deg2rad(-90)

If you have a Vector2 with the direction the player is moving towards, then you can calculate the angle from the direction and the use that as the rotation. For example, if you have a velocity:

func _physics_process(delta):
	# only rotate if we are moving
	if velocity.length_squared() > 0:
		global_rotation = atan2(velocity.y, velocity.x)
		# or (functionally the same)
		#global_rotation = velocity.angle()

For 3D, it's a bit harder because there are three axis of rotation. I find the easiest way to have rotation to look at a direction is to use the look_at function and then pass the position of the object, plus the offset that is the direction you want the object to look at. Something like this:

func _physics_process(delta):
	if Input.is_action_just_pressed(input_name_here):
		look_at(global_transform.origin + Vector3.FORWARD, Vector3.UP)
	
	# for velocity
	# generally we want to only rotate on the Y axis, so the player spins, so we'll need to remove the vertical component of the velocity
	var h_velocity = velocity * Vector3(1, 0, 1)
	if h_velocity.length_squared() > 0:
		look_at(global_transform.origin + h_velocity.normalized(), Vector3.UP)

However, the look_at function assumes a forward direction of -Z, so your player will need to be looking at that direction with zero rotation for it to work correctly. You can adjust any model to look in this direction by making it a child of a Spatial node and then rotating the parent Spatial instead of the mesh/node directly.

a year later