hii, I want to do somethings similar to the video. I can already move my player with basic movement but I have no idea how to do knockback for the player in a 2d game. And I can’t find tutorials on youtube. It’s mybe to advance for a beginner idk. I’m new in coding
So I would like a code for the gun and the knockback pleaaase, if needed I can send what i have already code !
Quick, semi-related tip: It will be much easier to read your code if you highlight all of it in the post editor, and then press the </> button. That’ll syntax highlight it and make sure the indentation is preserved.
So, in pseudo code, you’ll need something along the lines of:
if player pressed shoot button:
shoot_dir = direction of shot
knockback_dir = -shoot_dir
velocity = knockback_dir * knockback_speed
spawn a bullet and set its velocity to shoot_dir * bullet_speed
Where knockback_speed is some large-ish number.
However, with the way your code looks now, the velocity on the X axis will instantly be reset based on horizontal_direction, so you’ll need to check whether or not the player is on the ground before allowing them to move horizontally. You already know the is_on_floor()-function, so I’m sure you can figure that part out.
I was thinking player, since it’s the player that should be moved, but maybe the code that spawns bullets and such is better placed in the weapon script.
@export var knockback_speed = 1000
var knockback_direction : Vector2
var shoot_direction : Vector2
if Input.is_action_just_pressed("shoot"):
knockback_direction = -shoot_direction
velocity = knockback_direction * knockback_speed
#spawn a bullet and set its velocity to shoot_dir * bullet_speed
For the moment I have this and when I shoot when I fall I lose velocity, and I dont know what to do next.
Finally I would like to still be able to move when I’m not on the floor, not like the video