Godot Version
4.3
Question
I am having trouble figuring out how to rotate a 2D Sprite based on my movement. Here is my code β
extends CharacterBody2D
@export var _rotation_speed : float = TAU * 2
var _theta : float
var _direction : Vector2
func move(direction : Vector2):
_direction = direction
func _physics_process(delta : float):
var input_vector = Vector2.ZERO
input_vector.x = Input.get_action_strength("ui_right") - Input.get_action_strength("ui_left")
input_vector.y = Input.get_action_strength("ui_down") - Input.get_action_strength("ui_up")
input_vector = input_vector.normalized()
print(input_vector)
if _direction:
_theta = wrapf(atan2(_direction.y, _direction.x) - rotation, -PI, PI)
rotation += clamp(_rotation_speed * delta, 0, abs(_theta)) * sign(_theta)
if input_vector:
velocity = input_vector * 300
else:
velocity = input_vector
move_and_slide()
Thank you for your time,
SalladShooter
KingGD
January 26, 2025, 5:10am
2
You can do it like this:
sprite_2d.rotation = lerp_angle(sprite_2d.rotation, atan2(-velocity.x, -velocity.y), delta*10.0)
Thanks, but where should I put the line inside my code? I seem to get an error that says Invalid access to property or key 'rotation' on a base object of type 'CharacterBody2D'.
Do I need to instead put this code inside my Sprite2D
node or CharacterBody2D
node?
1 Like
KingGD
January 26, 2025, 1:55pm
4
Yeah, in sprite 2d, thatβs what you wanted?
Sorry, I meant my CharacterBody2D
My node tree is set up like this β
Node2D
|CharacterBody2D
|CollisionShape2D
|Sprite2D
KingGD
January 26, 2025, 3:02pm
6
Well then do like this:
rotation = lerp_angle(rotation, atan2(-velocity.x, -velocity.y), delta*10.0)
Or if it throws error, then please tell me the whole error not incomplete.
1 Like
Thanks for your help! Sorry, for the extra question, how could I make the rotation instant?
1 Like
KingGD
January 26, 2025, 3:12pm
8
Try to increase the 10.0
, which is multiplied with delta.
1 Like