Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Enemy Detection

Discussion in '2D' started by Deleted User, Sep 16, 2016.

  1. Deleted User

    Deleted User

    Guest

    Hi everyone, I'm very new to making games and coding so i started watching some tutorials online. I'm pretty deep in making my game and now I'm working on the enemies (flying), but the way my script has it is the enemy just takes your position(wherever you may be) and moves to it(explodes on contact with you). And there's nothing wrong with that except that this is a side scrolling game and i don't want the enemies to move to me until i am a certain distance from them. Is there a way i can do this?
    I have 3 enemy scripts what should i change to get the effect that i need?
     

    Attached Files:

  2. vakabaka

    vakabaka

    Joined:
    Jul 21, 2014
    Posts:
    1,153
    you can check the distance between player and enemy and then move the player if the distance is lower as you want.
    The distance can be calculated from vector from enemy to player. This vector is vector subtraction: end point - start point. Magnitude of this vector is the distance. I think, EnemyAI is your moving script. In C# you will need float variable for distance when enemy should move (you can change it later in inspector). Place the line in EnemyAi somewhere at 28 line.
    Code (CSharp):
    1. public float distanceToPlayer = 5;
    Then check the distance, befor moving your player and move, if magnitude of vector between enemy and player is smaller then your "distanceToPlayer". Replace 109 line.
    Code (CSharp):
    1. if (Vector3.Magnitude (target.transform.position - transform.position) < distanceToPlayer) {
    2.             rb.AddForce(dir, fMode);
    3.         }
    I am not sure, that it will work at first run, maybe something is wrong :)

    and check Unity manual (you should use sqrMagnitude to avoid extra cpu calculating):
    https://docs.unity3d.com/Manual/DirectionDistanceFromOneObjectToAnother.html
     
    Last edited: Sep 16, 2016