B
B
BaLahmuT2021-11-04 00:57:13
C++ / C#
BaLahmuT, 2021-11-04 00:57:13

How to do top, right, left damage in a 2D game?

The enemy is killed if you jump on top of him, initially the problem was that the damage during the jump was inflicted on both the enemy and the player, fixed it, but now there is another problem, when the enemy moves from the left side, then no damage is done, but if it is applied from the right (2 hearts) . what is needed so that the damage passes on the right side
. Here is the script for receiving damage, assigned to the enemy and the player:

public class CollisionDamage : MonoBehaviour
{
    public int damage = 10;
    public string collisionTag;

    GameObject enemy;
    GameObject player;

    private void OnCollisionEnter2D(Collision2D coll)
    {
        Health healthE = enemy.GetComponent<Health>();
        Health healthP = player.GetComponent<Health>();

        if (coll.gameObject.CompareTag(collisionTag)) //tag enemy
        {
            foreach (ContactPoint2D point2D in coll.contacts)
            {
                if (point2D.normal.y >= 0.5f)
                {
                    //Destroy(enemy.gameObject);                    
                    healthE.takeDamage(damage);
                }
                if (point2D.normal.x >= 0.5f)
                {
                    healthP.takeDamage(damage);
                }
            }
        }
    }

    private void Start()
    {
        enemy = GameObject.FindWithTag("Enemy");
        player = GameObject.FindWithTag("Player");  //GameObject.FindGameObjectWithTag("Player");
    }
}

I agree, maybe I'm not doing it right, but what to do in this situation? does the problem occur when the enemy changes sides (flipX)?
618305b018850639218848.png

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Vodakov, 2021-11-04
@WaterSmith

if (point2D.normal.x >= 0.5f)
                {
                    healthP.takeDamage(damage);
                }

I suspect that when colliding from the left, point2D.normal.x is less than 0.5

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question