0 votes

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:

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
    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)
        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:

Collision working

What sometimes happens: (Although usually only once or twice in a row and then works)

enter image description here

Godot version 3.2.3
in Engine by (24 points)

1 Answer

0 votes
Best answer

I think I fixed it by putting an Area2D with it's own CollisionShape as a child of the Kinematic body and then detecting with a signal when a body enters the area rather than when something collides with the kinematic body

by (24 points)
selected by
Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to webmaster@godotengine.org with your username.