Topic was automatically imported from the old Question2Answer platform.
Asked By
Jutoend
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:
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.
Compute angle after sprite travels some distance - prevents spinning in place
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)
That was a really enlightening answer! Thank you very much!!