sprite flip not working

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

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?

:bust_in_silhouette: Reply From: IceExplosive

Problem is, that you rotate the object in it’s local coordinates → so the mouse local_mouse_position 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.

thank you for your help

dverkh | 2021-07-09 21:34

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

Snail0259 | 2021-07-09 23:03