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. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

Facing Target Problem

Discussion in 'Scripting' started by Loff, Dec 4, 2018.

  1. Loff

    Loff

    Joined:
    Dec 3, 2012
    Posts:
    81
    Hey,

    I have a GameObject (Player) and a second GameObject (Enemy).
    I try to find out if the player is facing the Enemy

    It's basically just a cone in front and check if Target is within it. Cone is calculated with Angle & max Distance
    Getting the the distance is fine, but checking if Target is within the angle is my issue.

    Image example: https://imgur.com/a/KYEVtLL

    Tried a lot of different things like below to get angle, no luck
    Code (CSharp):
    1. Vector3 targetDir = -transform.position + Target.transform.position;
    2.             float angle = Vector3.Angle(targetDir, transform.right);
    Transform.right is correct as that's "front" for my gameObject's sprite.
    Code (CSharp):
    1. Debug.DrawRay(transform.position, transform.right, Color.red, 25f);
    Confirms that

    Bugged - I can't remove the two broken Images I added.
     
    Last edited: Dec 4, 2018
  2. SparrowGS

    SparrowGS

    Joined:
    Apr 6, 2017
    Posts:
    2,536
    I'd use a dot product for this.
    But im not sure how this applies to 2D.
     
  3. Loff

    Loff

    Joined:
    Dec 3, 2012
    Posts:
    81
    used this video to solve my problem :)