Search Unity

Navigation on a Sphere

Discussion in 'Navigation' started by SkinnyDinner, Nov 25, 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):
    1.     Vector3 SphereDirection (Vector3 from, Vector3 to, float maxMag = 1)
    2.     {
    3.         float angle = Vector3.Angle(from, to) * Mathf.Deg2Rad;
    4.         if (angle == Mathf.PI / 2)
    5.         {
    6.             return to;
    7.         }
    8.         float a = from.magnitude;
    9.         float h = a / Mathf.Cos(angle);
    10.         var forwardPos = to.normalized * h;
    11.         var direction = forwardPos - from;
    12.         direction = Vector3.ClampMagnitude(direction,maxMag);
    13.         if (angle > Mathf.PI / 2)
    14.             direction = -direction;
    15.         return direction;
    16.     }