Godot Version
4
Question
how can i make my player get hit back when being attacked by enemys?
thx
Hi, can you provide more details? Is your game 2D or 3D? What nodes are you using for the player and enemies?
ya its a 2d rpg game
code player:
extends CharacterBody2D
@onready var Enemy: AnimatedSprite2D = $enemy
@onready var animated_sprite_2d: AnimatedSprite2D = $Area2D/AnimatedSprite2D
const SPEED = 30
var isAttaking=false
var hit = false
var cool=false
var health=5
func get_input ():
var input_direction := Input.get_vector(“ui_left”, “ui_right”,“ui_up”,“ui_down”)
velocity=input_direction*SPEED
if Input.is_action_just_pressed("space")and isAttaking == false and (velocity.x>1 || velocity.x<-1):
isAttaking=true
animated_sprite_2d.animation="slice"
await get_tree().create_timer(0.25).timeout
isAttaking=false
if Input.is_action_just_pressed("space")and isAttaking == false and (velocity.y<-1):
isAttaking=true
animated_sprite_2d.animation="slice up"
await get_tree().create_timer(0.25).timeout
isAttaking=false
if Input.is_action_just_pressed("space")and isAttaking == false and (velocity.y>1 ||velocity.y==0 && velocity.x==0):
isAttaking=true
animated_sprite_2d.animation="slice down"
await get_tree().create_timer(0.25).timeout
isAttaking=false
if (velocity.x>1 || velocity.x<-1) and isAttaking==false:
animated_sprite_2d.animation="move side"
else :
if (velocity.y<-1) and isAttaking==false:
animated_sprite_2d.animation="move up"
if (velocity.y>1) and isAttaking==false:
animated_sprite_2d.animation="move down"
if (velocity.x==0 && velocity.y==0)and isAttaking==false:
animated_sprite_2d.animation="default"
func _physics_process(delta):
get_input()
move_and_slide()
var isLeft = velocity.x<0
animated_sprite_2d.flip_h = isLeft
func _on_hit_box_plater_body_entered(body: Node2D) → void:
if body.is_in_group(“enemy”):
decrease_health()
func decrease_health():
health-=1
animated_sprite_2d.animation=“hit”
isAttaking=true
await get_tree().create_timer(0.05).timeout
isAttaking=false
if health<=0:
get_tree().change_scene_to_file("res://start.tscn")
It looks like you already have a function to detect if an enemy enters the player’s hitbox. You can also set a variable here that indicates that the player is taking knockback, set the velocity based on the direction from the enemy to the player, and disable input for that duration. It might be complicated to add another variable you need to keep track of, so it might be easier to use a state machine.
how should i code that?