How to make Node stops shaking when rotating at global_mouse_position?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: 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:

	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.

:bust_in_silhouette: Reply From: Bartosz

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)

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

Jutoend | 2018-03-29 23:35