I have a kinematicbody2D enemy that is supposed to play a death animation when it gets hit by a ball. I move the enemy with moveandslide, and then detect collisions with getslidecount and use a for loop to only get the collision when the enemy hits the ball and not the floor.
Sometimes the death animation plays and sometimes the ball just bounces off.
The ball moves with moveandcollide in its own script
Here's my code:
var velocity = Vector2(0,0)
var direction = 1
export var moveSpeed = 150
var alive = true
var deltaX = 0
var soundPlayed = false
# Called when the node enters the scene tree for the first time.
gravity = get_node("/root/Node2D").gravity
originalPos = position.x
#splatSound= preload("res://Sounds/Blood splat.wav")
# Called every frame. 'delta' is the elapsed time since the previous frame.
velocity.y += gravity * delta
velocity.x = moveSpeed * delta * direction * 60
velocity = move_and_slide(velocity)
if (get_slide_count() > 0):
for i in range(get_slide_count()):
var collision = get_slide_collision(i)
if (collision.collider.name == 'KinematicBall'):
alive = false
deltaX = position.x - originalPos
if (abs(deltaX) >= 200):
direction = -direction
$EnemyCollision.disabled = true
if(soundPlayed == false):
$EnemyAudioPlayer.stream = load("res://Sounds/Blood splat.wav")
soundPlayed = true
How it is supposed to work:
What sometimes happens: (Although usually only once or twice in a row and then works)