How do i rotate node toward where mouse click ?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By atopetrick

i’m creating simple tank demo game. In scene player tank is centre-bottom position. now when use click on any area of game screen tank will be rotate toward that points.

i checked look_at() function but its effect is instant i want slowly animation of rotation.

e.g player point toward top-right direction now user click at left-top direction than tank should rotate to left-top direction.

Tank Structure is:

---- CollisionShape2D
---- Sprite

Does anyone have any idea how i can do this? Any link , tutorial or code will be helpful.

Thank you.

:bust_in_silhouette: Reply From: flurick

If the tank is stationary using a lerp() towards a varaible taraget rotation would work, but angles do not wrap around between 0 to 360 so the aim would turn multiple turns until it would catch up with the rotation.

This seems to work as expected even at rotating more then 180 degrees.

var target_angle = 0
var turn_speed = deg2rad(3)

func _process(delta):
	var dir = $barrel.get_angle_to( get_global_mouse_position() )
	if abs(dir)<turn_speed: #to close for full turn_speed
		$barrel.rotation += dir #this is just a look_at
		if dir>0: $barrel.rotation += turn_speed #clockwise
		if dir

Thanks man :slight_smile: this is working great . i just update it for both clockwise and ant-clockwise.

    var dir = get_angle_to(get_global_mouse_position())
	if abs(dir) < turn_speed:
		rotation += dir
		if dir>0: rotation += turn_speed #clockwise
		if dir<0: rotation -= turn_speed #anit - clockwise

atopetrick | 2019-03-16 05:06

Registered just to upvote this answer: worked perfectly for me! Thanks!

Stingly | 2020-05-18 14:33