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

Question set position relative to angle in 2d

Discussion in 'Scripting' started by Extra_, May 22, 2023.

  1. Extra_

    Extra_

    Joined:
    Nov 26, 2022
    Posts:
    12
    hello, let's say my enemy is 37 degrees and 15m from my player. is there a way to set it so let's say his y is 0.7 and his x is 0.8, so the angle between then will be 37 degrees?
    soory for bad english.
     
  2. Elhimp

    Elhimp

    Joined:
    Jan 6, 2013
    Posts:
    71
  3. orionsyndrome

    orionsyndrome

    Joined:
    May 4, 2014
    Posts:
    3,043
    Code (csharp):
    1. var myEnemyPos = atDistance(15f, toCartesian(toRadians(37f)));
    where
    Code (csharp):
    1. Vector3 atDistance(float distance, Vector3 direction) => distance * direction;
    2. float toRadians(float angle) => angle * Mathf.Deg2Rad;
    3. Vector3 toCartesian(float radians) => new Vector3(MathF.Cos(radians), MathF.Sin(radians), 0f);
    To understand this learn more about unit circle and radians, as well as vectors and directions. There are plenty of resources online.

    Same code, more compactly
    Code (csharp):
    1. var radians = angle * Mathf.Deg2Rad;
    2. var myEnemyPos = 15f * new Vector3(MathF.Cos(radians), MathF.Sin(radians), 0f);
    The solution is on the XY plane. For XZ plane, obviously switch the arguments around.