Question about local_mouse_position?

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

So i want want a KinematicBody2D node to rotate to the direction of the vector i created and i was able to accomplish this with the code:

extends KinematicBody2D
var vec_start := Vector2.ZERO
var vec_fin := Vector2.ZERO

func _physics_process(delta):

     			   #NODE ROTATION
if Input.is_action_just_pressed("ui_touch"):
	vec_start = get_global_mouse_position()
	vec_fin = vec_start
	
if Input.is_action_pressed("ui_touch"):
	vec_fin = get_global_mouse_position()
	rotation = ((vec_start - vec_fin).normalized()*100).angle()

But since the KinematicBody2D node is also moving the global_mouse_position is being updated and messing up the vector so i think need to use local_mouse_position which i think dosen’t update even if the node moves

func _physics_process(delta):
     			   #NODE ROTATION
if Input.is_action_just_pressed("ui_touch"):
	vec_start = get_local_mouse_position()
	vec_fin = vec_start
	
if Input.is_action_pressed("ui_touch"):
	vec_fin = get_local_mouse_position()
	rotation = ((vec_start - vec_fin).normalized()*100).angle()

But that code just doesn’t work for some reason and the node just starts spinning instead of rotating in the direction of the vector

How do i fix this???

:bust_in_silhouette: Reply From: DaddyMonster

Use vec_fin = get_viewport().get_mouse_position() instead and minus it from the global position of your object to get the vector between them and take the angle:

rotation = (vec_fin - obj.global_position).angle()

Honestly though, you could just use the inbuilt obj.look_at(vec_fin)and save yourself the effort.

I tried using this but it isn’t working:

func _physics_process(delta):
      
    			   #NODE ROTATION
  if Input.is_action_just_pressed("ui_touch"):
	 vec_start = global_position
	 vec_fin = vec_start
	
  if Input.is_action_pressed("ui_touch"):
	 vec_fin = get_viewport().get_mouse_position()
	 rotation = (vec_fin - vec_start).angle()

javrocks | 2021-09-24 13:14

Run this and tell me what happens:

func _physics_process(_delta):
     vec_start = global_position
     vec_fin = get_viewport().get_mouse_position()
     rotation = (vec_fin - vec_start).angle()

DaddyMonster | 2021-09-24 13:59

i think its working now

javrocks | 2021-09-24 16:09