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

How to spot enemy a player?

Discussion in 'Scripting' started by huseyinbaba58, Aug 14, 2020.

  1. huseyinbaba58

    huseyinbaba58

    Joined:
    Feb 12, 2020
    Posts:
    146
    I would like to when enemy patrols the area, enemy has to spot player and player has to avoid enemy for not taking damage.
    How can I do it?
     
  2. Yanne065

    Yanne065

    Joined:
    Feb 24, 2018
    Posts:
    175
    There's so many way ... why don't you try google
     
  3. adehm

    adehm

    Joined:
    May 3, 2017
    Posts:
    369
    Easiest way to start would to be to check if player is within a circle of enemy center point. If that is true then you can check for obstruction inbetween the two points.
    Code (CSharp):
    1. /*
    2. using 2 dimensions. So if this is 3D then y would be z and I'm not going to tackle if things are layered on top of eachother.
    3. player.x and player.y are the center point of the player.
    4. enemy.x and enemy.y are the center point of the enemy.
    5. radius is the distance from the center of the enemy to the edge of detection.
    6. */
    7. //calculate distance.
    8. float distance = (player.x - enemy.x) * (player.x - enemy.x) + (player.y - enemy.y) * (player.y - enemy.y);
    9. //check if player in range.
    10. if (distance <= radius * radius)
    11. {
    12.    //player detected
    13. }
     
  4. huseyinbaba58

    huseyinbaba58

    Joined:
    Feb 12, 2020
    Posts:
    146
    I tried .Then I asked this forum.
     
  5. huseyinbaba58

    huseyinbaba58

    Joined:
    Feb 12, 2020
    Posts:
    146
    Thanks sir.