Search Unity

Move RB through any place on gate [not center]

Discussion in 'Scripting' started by kai_226, Feb 11, 2018.

  1. kai_226

    kai_226

    Joined:
    Jul 6, 2017
    Posts:
    53
    Hi,

    I have a space ship with a RigidBody and I have a gate in the distance. I want the RB to go through the gate. Currently I am using this to calculate the turn ratio:

    Code (CSharp):
    1. void Update () {
    2.     angleToNextGate = GetAngleToNextGate();
    3.  
    4.         /* angleToNextGate
    5.             * ===============
    6.             * Next Gate is left = Positive angle -> dirPicker = -1f
    7.             * Next Gate is Right = Negative angle -> dirPicker = 1f
    8.             * */
    9.            
    10.         //  FlightController axis values go from 0f to 1f
    11.         AccelerateDependingOnAngle();
    12.         Steering();
    13. }
    14.  
    15. #region Path calculations
    16. float GetAngleToNextGate()
    17. {
    18.     Vector3 dir = Vector3.zero;
    19.     float angle = 0f;
    20.  
    21.     if (Nav.nextGate != null)
    22.     {
    23.         dir = Nav.nextGate.transform.position - transform.position;
    24.         angle = Vector3.Angle(dir, transform.forward);
    25.         dir = Vector3.Cross(dir, transform.forward);
    26.  
    27.         if (dir.y < 0)
    28.         {
    29.             angle = -angle;
    30.         }
    31.     }
    32.  
    33.     return angle;
    34. }
    35. #endregion
    36.  
    37. #region Controls
    38. void AccelerateDependingOnAngle()
    39. {
    40.     if (Mathf.Abs(angleToNextGate) < 60f)
    41.     {
    42.         FC.axisValueAccelerate = 1f;
    43.     }
    44.     else
    45.     {
    46.         FC.axisValueAccelerate = 0f;
    47.     }
    48. }
    49.  
    50. void Steering()
    51. {
    52.     if (angleToNextGate < 0f)
    53.     {
    54.         dirPicker = 1f;
    55.     }
    56.     else
    57.     {
    58.         dirPicker = -1f;
    59.     }
    60.  
    61.     if (Mathf.Abs(angleToNextGate) > 40f)
    62.     {
    63.         FC.axisValueSteer = dirPicker;
    64.     }
    65.     else
    66.     {
    67.         FC.axisValueSteer = dirPicker * Mathf.Abs(angleToNextGate) / 40f;
    68.     }
    69. }

    This works very good when the RB is far away from the gate. However, the gate is wide and if the ship approaches from the left for example, I want the ship to go through the left part of the gate and not flying to the center of the gate first.
    Kinda like optimizing a race line, to go through the spot in the gate that is the shortest way instead of going through the center of the gate.

    I was thinking in approaching to the center first when the ship is far and when it reached a certain distance, not focusing on the center any more but the shortest path. Any ideas how to calculate that?
    Side note: Not all gates have the same width.