Home > Software design >  How can I make it so that the player loses health when an enemy collides with a different object?
How can I make it so that the player loses health when an enemy collides with a different object?

Time:02-15

Here an image of what my game looks like so far so that you can get a better idea but I need it so that when one of the outer capsules touches the red box the player (middle capsule) loses health.

I have tried creating a new script which checks for collisions but I couldn't get it to work and am unsure where to go from here. Below is my code for how the health bar works and pressing the space bar reduces health for demonstration purposes.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class PlayerHealth : MonoBehaviour
{
    public float MaxHealth;
    public Slider _slide;
    private float currentHealth;

    void Start()
    {
        currentHealth = MaxHealth;
        _slide.maxValue = MaxHealth;
        _slide.value = MaxHealth;
    }

    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Space))
            TakeDamage(25f);

        if(currentHealth <=0)
        {
            //move to game over
        }
    }

    void TakeDamage(float Damage)
    {
        currentHealth = currentHealth - Damage;
        _slide.value = currentHealth;
    }
}

At one point I tried using

    void Update()
    {
        (collision.collider.name == "Barrier");
            TakeDamage(25f);

        if(currentHealth <=0)
        {
            //move to game over
        }
    }

but realised this is completely wrong, as well as trying to add a box collider to the red "barrier" to aid this but it didn't fix anything.

Update 2: Also tried changing it so that the enemies move towards the barrier and not the player and added the code:

    private void OnTriggerEnter(Collider other) {
        TakeDamage(25f);

        if(currentHealth <=0)
        {
            //move to game over
        }
    }

which doesn't present any errors but rather just doesn't do anything. The enemy capsules just go through it and to the centre, with no health being lost.

CodePudding user response:

You need to check for collisions using OnCollisionEnter2D and then use the TakeDamage function inside of it. Here is an example:

public class PlayerHealth: MonoBehaviour
{
    void OnCollisionEnter2D(Collision2D col) //Check for 2d collision
    {
        TakeDamage(25f);
    }
}

Note that for this function to work, both objects need a 2d collider and a rigid body. If you don't want your character to fall, just set gravity to 0.

  • Related