0 votes

I am making a simple 2d game and was trying to make a gun rotation script. The gun needs to flip when the cursor is on the left side of the screen.
This is the code I am using:

extends Sprite

var mouseposition

func _process(delta):
    mouseposition = get_local_mouse_position()
    set_flip_v(mouseposition.x <= 0)

The gun flips as it should but then I add this line:

    rotation += mouseposition.angle()

After this the gun starts to rotate but the flip line doesn’t seem to work.
What am I doing wrong?

Godot version v3.3.2
in Engine by (15 points)

1 Answer

0 votes
Best answer

Problem is, that you rotate the object in it's local coordinates -> so the mouse localmouseposition is not what you expect.

One solution is to compare mouse_global with object's global:

mouseposition = get_global_mouse_position() - global_position;
rotation = mouseposition.angle();
set_flip_v(mouseposition.x <= 0);

The other (better) is to rotate the object within global's space:

mouseposition = get_local_mouse_position()
set_flip_v(mouseposition.x <= 0)
global_rotation += mouseposition.angle()

Generaly it's better to alter globals, not locals -> because moving object in local will affect it's collisions local_mouse and many more things.

by (195 points)
selected by

thank you for your help

Make sure you set their answer as 'best answer' if it solved your problem! (So that everyone knows it's a good answer)

Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to webmaster@godotengine.org with your username.