How can i make a in orbit object follow my mouse position?

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

Hi guys, in my game I want the weapon to be around the player, in their orbit. I’ve tried several possible ways and the most I could get was the following:

func _process(delta):
get_input()
move_weapon()

func move_weapon():
mouse_position = get_local_mouse_position()
$AnimatedSprite/Gun.rotation = mouse_position.angle()

With this code, my weapon moves along with the mouse, but doesn’t point where it is.

Thanks in advance.

:bust_in_silhouette: Reply From: Pomelo

As I understand, what your code achieves is that the gun does rotate along with the mouse (asuming the parent dosnt rotate). The only thing that could be bothering you is that, there is a visual “offset” at where the pointy stick of the gun is looking at. If thats the case, you will have to either go to the gun scene and make sure the pointy bit is looking exactly at the right ( I think), or find the amount of rotation offset value you are lacking and add it like so

var gun_rot_offset = some_value_you_have_to_find 
$AnimatedSprite/Gun.rotation = mouse_position.angle() + gun_rot_offset

Hope it helps!

Thanks man, it worked perfectly!

Matt101 | 2022-06-08 13:53

:bust_in_silhouette: Reply From: CassanovaWong

Well, I’m a little unclear on what your question is. Do you just want the gun to point at the mouse, or are you trying to actually have the gun’s position, constrained by a specified perimeter, around your player?

Or both?

For starts, to fix that rotation bit, I’d just rewrite the code as :

onready var gun = $AnimatedSprite/Gun

func _physics_process(delta):
    get_input()
    move_weapon()

func move_weapon():
    gun.rotation = gun.position.get_angle_to(get_local_mouse_position())

Or, even easier:

func move_weapon():
    gun.look_at(get_local_mouse_position())

And, if you do want it be constrained by an orbit around the player, I’d use something like:

onready var gun = $AnimatedSprite/Gun
var perimeter_radius:float

func _physics_process(delta):
    get_input()
    move_weapon()

func move_weapon():
    gun.position.x = clamp(gun.position.x, player.position.x-perimeter_radius, player.position.x+perimeter_radius)
    gun.position.y= clamp(gun.position.y, player.position.y-perimeter_radius, player.position.y+perimeter_radius)
    gun.look_at(get_local_mouse_position()