Godot Version
4.4.1
Question
I’ve got a rotation issue here with my gun. It likely stems from the classic 180 vs -180 degree issue.
Here’s my code (snippet):
var aim_direction = (get_global_mouse_position() - global_position).normalized()
pistol.position = aim_direction * 125
pistol.rotation = wrapf((aim_direction.angle() + previous_gun_tilt)/2,-PI,PI)
pistol.flip_v = (aim_direction.x < 0)
previous_gun_tilt = move_toward(previous_gun_tilt,pistol.rotation,delta*5)
My OBS isn’t working so I unfortunately can’t record the behaviour, but it should be quite simple to reproduce. It’s just this code in _process() and “pistol” is a Sprite2D as a child of a CharacterBody2D.
I’d suggest fposmod(value, TAU)
rather than wrapf(value, -PI, PI)
.
1 Like
The behaviour still occurs… thanks for trying though
What is “the behavior”? I’m not in front of a machine with godot on it at the moment.
The gun ends up flipped vertically in the top left quadrant and sometimes faces straight ahead rather than pointing at the intended angle.
There are several possible things here:
- if
aim_direction
is a zero vector, all sorts of fun stuff could happen
- mixing in
previous_gun_tilt
means if something goes weird with aim_direction
it may take a while to shake out
- you might want to pull out that
5
and call it const AIM_SPEED: float = 5.0
or the like
- your rotation is mixing previous and desired positions, but your position is set immediately with no mixing, which means they’re not really going to be in agreement if the mouse is moving
I see. While waiting for your reply, I decided to adjust some things and make a simpler system that performs more or less the same task:
var aim_direction = (get_global_mouse_position() - global_position).normalized()
pistol.position = aim_direction * 125
pistol.rotation = move_toward(fposmod(pistol.rotation,TAU),fposmod(aim_direction.angle(),TAU),delta*5)
pistol.flip_v = (aim_direction.x < 0)
This setup does the job, but I figured out the issue in it: when going from a value of about 360 back to 0, it does a full spin the other way. Is this a job for fposmod?
I fixed it! I used the rotate_toward() function with the functionality built-in.
1 Like