How to make gun kickback in 2D?

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

Hi
I’m not sure if Godot has a built-in function for this or not, but I’ve tried to make something like the “lengthdir” function from GameMaker and although it works, it doesn’t look as smooth and has some issues.

https://i.imgur.com/xRPUsqg.gif

As you can see, when I’m shooting in a straight line, it’s fine, but as soon as I rotate the character (while shooting), it does a weird animation.

func shoot():
  if can_shoot:
	can_shoot = false
	var dir = Vector2(1, 0).rotated($Sprite/shootspot.global_rotation) 
	var kick = 200
	var kickdirection = (rad2deg(dir.angle())) - 180
	velocity.x = velocity.x + (kick * cos(kickdirection))
	velocity.y = velocity.y + (kick * -sin(kickdirection))
:bust_in_silhouette: Reply From: DavidPeterWorks

You should decrease the velocity in _process function.
I use a simple way to do it. That would decrease velocity rapidly.
velocity = velocity *0.7

What does decreasing the velocity has anything to do with shoot kickback? I tried what you suggested but didn’t make any difference.

I’m guessing it has something to do with these 2 lines??:

velocity.x = velocity.x + (kick * cos(kickdirection))
velocity.y = velocity.y + (kick * -sin(kickdirection))

Thanks.

DFSHINNOK7 | 2019-05-05 17:04

What about something like this? Without cos and sin.
You need the opposite direction.

func shoot():

  if can_shoot:
    can_shoot = false
    var dir = Vector2(1, 0).rotated($Sprite/shootspot.global_rotation) 
    var kick = 200
    var kickdirection = kick * (dir*-1)
    velocity = velocity + kickdirection


func _process(delta):
  body.position += velocity
  velocity = velocity *0.7

DavidPeterWorks | 2019-05-05 17:36