I am making a gun that shoots projectiles and i want it to have recoil too. I make the camera rotate a bit upwards every time you shoot. The issue is that by doing that the locking position of the camera (90 to -90 degrees) changes. In a 30 round mag, the camera lock would be (180 to -180 degrees). If you want more clarification let me know in the comments. Here is the code:
recoil code
#add recoid
func recoil():
camera.rotate_x(rad2deg(0.001)) # rotate the camera
fired += 1 #keep track how many shots have fired without letting the trigger down. It starts with zero
firing code
if can_fire == true and magazines[0]>0:
bullet_add()#irrelevant code
case_add()#irrelevant code
recoil()#calling recoil code
magazines[0] = magazines[0] -1#irrelevant code
ammo=magazines[0]#irrelevant code
print(magazines)#irrelevant code
can_fire = false#irrelevant code
yield(get_tree().create_timer(fire_rate), "timeout")#irrelevant code
can_fire = true#irrelevant code
camera code:
func _input(event):
var heat = gun.fired # accese the fired var from the recoil function
if event is InputEventMouseMotion:
player.rotate_y(deg2rad(-event.relative.x * mouse_sensitivity)) #irrelevant code
var x_delta = event.relative.y * mouse_sensitivity #get the angular speed for the y axis
print(x_delta)
if camera_x_rotation + x_delta > -90 and camera_x_rotation + x_delta < 90: #lock the camera between 90 and -90 degrees
camera.rotate_x(deg2rad(-x_delta)) #rotate camera
camera_x_rotation += x_delta #tbh i dont remember
possible solution: rotate the camera back to the start position when you left the fire button. It isn't really realistic thought and i dont know how awkward it would be for the player (the code is called on the physics_process function
#remove recoil
func remove():
if Input.is_action_just_released("shoot"): #check if fire button is released
camera.rotate_x(rad2deg(-fired*0.001)) # change the camera rotation based on how many shots fired by multiplying the fired var with negative the rotation
fired = 0 #resets fired var