Search code examples
c#unity-game-engine2d-games

How can i set an offset on my Enemy script so he can easy take a shoot


So i have a small code in my 2d game in unity that if my enemy's y position equal to my player's y position, then my Enemy will shoot a bullet, the thing is right now my enemy need exactly position to take a shoot, so is there anyway that i can add and offset to get this easier

if (target.position.y == boss.position.y)
        {
            Shoot();
        }


Solution

  • You can simply find the distance between two values by doing |x - y|

    var targetPosition = target.position.y;
    var enemyPosition = boss.position.y;
    var offSet = 3f;
    
    var shouldShoot = Mathf.Abs(targetPosition - enemyPosition) <= offSet;
    
    if(shouldShoot) {
        Shoot();
    }