Attention | Topic was automatically imported from the old Question2Answer platform. | |
Asked By | sanp03 | |
Old Version | Published before Godot 3 was released. |
At this point i’m able to place my attack “hitbox” scene for a split second before destroying itself with a timer when the character presses attack, how do I detect when it collides or enters another area2d?
My game has two players, and I want to have a knockback effect when one hits the other. Thanks in advance.
My code for player 1:
extends KinematicBody2D
var sprite_node
var anim = "idle"
var attack_node
var attacking
var attack = 0
var input_direction = 0
var direction = 1
var speed = Vector2()
var velocity = Vector2()
const MAX_SPEED = 350
const ACCELERATION = 2600
const DECELERATION = 5000
const JUMP_FORCE = 1000
const GRAVITY = 2300
const MAX_FALL_SPEED = 1400
var jump_count = 0
const MAX_JUMP_COUNT = 2
func _ready():
set_process(true)
set_process_input(true)
sprite_node = get_node("Sprite")
attack_node = preload("Attack.tscn")
func _input(event):
if jump_count < MAX_JUMP_COUNT and event.is_action_pressed("jump"):
speed.y = -JUMP_FORCE
jump_count += 1
func _process(delta):
if input_direction:
direction = input_direction
if Input.is_action_pressed("move_left"):
input_direction = -1
sprite_node.set_flip_h(true)
elif Input.is_action_pressed("move_right"):
input_direction = 1
sprite_node.set_flip_h(false)
elif Input.is_action_pressed("player1_attack"):
attack = 1
else:
input_direction = 0
attack = 0
if input_direction == - direction:
speed.x /= 3
if input_direction:
speed.x += ACCELERATION * delta
else:
speed.x -= DECELERATION * delta
speed.x = clamp(speed.x, 0, MAX_SPEED)
speed.y += GRAVITY * delta
if speed.y > MAX_FALL_SPEED:
speed.y = MAX_FALL_SPEED
velocity = Vector2(speed.x * delta * direction, speed.y * delta)
var movement_remainder = move(velocity)
if is_colliding():
var normal = get_collision_normal()
var final_movement = normal.slide(movement_remainder)
speed = normal.slide(speed)
move(final_movement)
if normal == Vector2(0, -1):
jump_count = 0
if attack == 1:
anim = "attack"
input_direction = 0
speed.x = 0
var attacking = attack_node.instance()
get_parent().add_child(attacking)
attacking.set_pos(get_node("Position2D").get_global_pos())
elif speed.y < 0:
anim = 'jump'
elif speed.y > 0:
anim = 'fall'
elif input_direction == 0:
anim = "idle"
else:
anim = "run"
sprite_node.play(anim)
Attack scene code:
extends Area2D
onready var timer = get_node("Timer")
func _ready():
set_fixed_process(true)
timer.connect("timeout", self, "queue_free")
timer.set_wait_time(0.2)
timer.start()
func _fixed_process(delta):
if timer.get_time_left() == 0:
queue_free()