This site is currently in read-only mode during migration to a new platform.
You cannot post questions, answers or comments, as they would be lost during the migration otherwise.
0 votes

I'm making a game where you control the character by clicking and dragging it. It rotates, pointing in the direction that it is been dragging to. I've done it with this two lines of code:

    angle = get_angle_to(get_global_mouse_position())
    rotate(angle)

But when I drag the player slowly, it shakes like the angle is changing a bit even if I try to keep the same direction.
I tried using look_at(mousepos), but it won't work when the character is clicked over.

in Engine by (35 points)
edited by

1 Answer

+2 votes
Best answer

Two advices:
1. Compute angle after sprite travels some distance - prevents spinning in place
2. use lerp for smoothing

here is code from demo on godot-recipes I 've made for your question:

extends Sprite

var dragging = false
var last_position

func _ready():
    $Area2D.connect("input_event",self,"area_event")
    last_position = global_position

func area_event(viewport,event,shape_idx):
    if event is InputEventMouseButton:
        if event.button_index == BUTTON_LEFT:
            dragging = event.pressed

func _process(delta):
    if dragging:        
        global_position = get_global_mouse_position()
        # rotating sprite to point in direction
        var position_delta = global_position - last_position

        # wait until we drag some distance to prefent spinning in place
        if position_delta.length() > 5:
            last_position = global_position

            # use lerp to smooth rotation over distance
            rotation = lerp(rotation,position_delta.angle(),0.2)
by (1,024 points)
selected by

That was a really enlightening answer! Thank you very much!!

Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read Frequently asked questions and How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to [email protected] with your username.