i kind of need help with this gun mechanic
func _process(delta: float) -> void:
var mouse_pos = get_global_mouse_position()
look_at(mouse_pos)
if rotation_degrees > 90 or rotation_degrees < -90:
scale.y = -1
else:
scale.y = +1
this the code , the problem i have is that after only one rotation the gun node doesnt tranform and flip, like if i want n number of rotation in that direction it doesnt work. im kind of new to game dev so i dont know much, im very sure this has a simple solution but i dont understand how to solve it.
when you run the game go to the top left above the scene tree and press remote and go to your gun node there you can watch the rotation degrees while you play the game when you do that youll notice that rotation continues counting up(or down) as you spin the node around what you probably want to track is the direction vector between the gun node and the mouse which would look something like this
#variable to reference the gun sprite
@onready var gun: Sprite2D = $"."
func _process(delta: float) -> void:
var mouse_pos = get_global_mouse_position()
#we subtract the position of the gun from the mouse to get the direction vector
var direction = mouse_pos - gun.global_position
look_at(mouse_pos)
#check the x component of the direction vector to flip the sprite
if direction.x > 0:
scale.y = 1
else:
scale.y = -1
this will flip the sprite when the mouse is to the left and right of the gun
1 Like
this is partially the solution but since it doesnt transform the node it would mean when im shooting a bullet it wont come out of the direction im aiming, tho this solution is also appreciated. im assuming i need to write a separate code which would work on the firing of the gun.
it depends on your scene tree and what node the script is attached to(im assuming the gun sprite). you could add to this script and spawn the bullet based off that direction variable as well with something like bullet = move_toward(direction.normalized() * bullet_speed)
this will set the bullets direction to the same as the gun
1 Like
thanks man this should help.
1 Like