Shoot in 2D, look_at() function

Godot Version

3.5.2 stable


I’m learning for myself and I’m trying to make a node point to the direction of the mouse, I just wanted to test how it would work using look_at(get_global_mouse_position) but although the object moves with the mouse, it points to an offset position.

The object I’m trying to move is a Node2D with 2 sprites (and an AnimationPlayer to make a recoil animation):


This scene is instanced in another scence called CannonBase with just a Sprite.

extends Node2D

onready var animacion = $AnimationPlayer

func _physics_process(delta):
var posicion = get_global_mouse_position()

if Input.is_action_pressed("Disparar"):"Disparo")
1 Like

There are two distinct problems you need to solve. First, the global mouse coordinates are relative to the CanvasLayer origin. This is a position that is not where your object is, so you need to take the difference. For that it’s actually easier to use local coordinates.

var pos = get_local_mouse_position() - position

The other part is look_at() assumes your sprite starts looking to the right (aka east, aka positive x). If your sprite is looking up, you need to subtract 90 degrees (aka PI/2, aka TAU/4 radians) to correct the rotation.
Finally, you don’t want to do this in the physics process specially since you’re extending Node2D, not a physics node.

1 Like

Thanks for your help!

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.