Attention | Topic was automatically imported from the old Question2Answer platform. | |
Asked By | Cahoots |
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 move_and_slide, and then detect collisions with get_slide_count 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 move_and_collide in its own script
Here’s my code:
extends KinematicBody2D
var gravity
var velocity = Vector2(0,0)
var direction = 1
export var moveSpeed = 150
var alive = true
var deltaX = 0
var originalPos
var soundPlayed = false
#var splatSound
# Called when the node enters the scene tree for the first time.
func _ready():
gravity = get_node("/root/Node2D").gravity
$EnemySprite.play("walk")
originalPos = position.x
#splatSound= preload("res://Sounds/Blood splat.wav")
# Called every frame. 'delta' is the elapsed time since the previous frame.
func _physics_process(delta):
if alive:
velocity.y += gravity * delta
velocity.x = moveSpeed * delta * direction * 60
velocity = move_and_slide(velocity)
print(get_slide_count())
print(velocity.slope_stop_min_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
else:
$EnemyCollision.disabled = true
$EnemySprite.play("death")
if(soundPlayed == false):
$EnemyAudioPlayer.stream = load("res://Sounds/Blood splat.wav")
$EnemyAudioPlayer.play()
soundPlayed = true
How it is supposed to work:
What sometimes happens: (Although usually only once or twice in a row and then works)