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

Cleanly navigating on a sphere

Discussion in 'Scripting' started by SkinnyDinner, Dec 8, 2020.

  1. SkinnyDinner

    SkinnyDinner

    Joined:
    Feb 13, 2016
    Posts:
    8
    I'm making a game in which the AIs move towards a target on a sphere, but I'm not really sure how to get it right. I've tried using vector3.rotatetowards, and that worked for the most part. But what I really want is to get a direction perpendicular to the vector between the character and the center of the sphere, eventually leading to the target position.

    I came up with this, but when it gets within one meter of the target, it seems to only move exponentially closer the target. Alternatively, normalizing the direction makes the AI sort of glitch back and forth past the target position.

    Code (CSharp):
    Vector3 SphereDirection (Vector3 from, Vector3 to, float maxMag = 1)
    {
    float angle = Vector3.Angle(from, to) * Mathf.Deg2Rad;
    if (angle == Mathf.PI / 2)
    {
    return to;
    }
    float a = from.magnitude;
    float h = a / Mathf.Cos(angle);
    var forwardPos = to.normalized * h;
    var direction = forwardPos - from;
    direction = Vector3.ClampMagnitude(direction,maxMag);
    if (angle > Mathf.PI / 2)
    direction = -direction;
    return direction;
    }
     
  2. exiguous

    exiguous

    Joined:
    Nov 21, 2010
    Posts:
    1,749
    I'm a bit concerned that you are registered here for almost 5 years and still don't know how to usw code tags properly?

    Navigation on a sphere (without obstacles) is usually done with great circles.
     
  3. SkinnyDinner

    SkinnyDinner

    Joined:
    Feb 13, 2016
    Posts:
    8
    I made my account five years ago, but i was quite inactive until recently and still busy with school. Thanks though!
     
  4. SkinnyDinner

    SkinnyDinner

    Joined:
    Feb 13, 2016
    Posts:
    8
    Sorry i read the page you linked to and i dont understand how this is supposed to help