Search Unity

3d Trajectory Help

Discussion in 'Scripting' started by imunirbesye, Apr 10, 2019.

  1. imunirbesye

    imunirbesye

    Joined:
    Oct 27, 2018
    Posts:
    57
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. [RequireComponent(typeof(LineRenderer))]
    6. public class LaunchArcRenderer : MonoBehaviour
    7. {
    8.     LineRenderer lr;
    9.  
    10.     public float velocity;
    11.     public float angle;
    12.     public int resolution = 10;
    13.  
    14.     float g;
    15.     float radianAngle;
    16.  
    17.     private void Awake()
    18.     {
    19.         lr = GetComponent<LineRenderer>();
    20.         g = Mathf.Abs(Physics.gravity.y);
    21.     }
    22.  
    23.     void Start()
    24.     {
    25.        
    26.     }
    27.  
    28.     private void Update()
    29.     {
    30.        
    31.     }
    32.  
    33.     public void RenderArc()
    34.     {
    35.         lr.positionCount = resolution + 1;
    36.         lr.SetPositions(CalculateArcArray());
    37.     }
    38.  
    39.     Vector3[] CalculateArcArray()
    40.     {
    41.         Vector3[] arcArray = new Vector3[resolution + 1];
    42.  
    43.         radianAngle = Mathf.Deg2Rad * angle;
    44.  
    45.         float maxDistance = (velocity * velocity * Mathf.Sin(2 * radianAngle)) / g;
    46.  
    47.         for(int i = 0; i <= resolution; i++)
    48.         {
    49.             float t = (float)i / (float)resolution;
    50.             arcArray[i] = CalculateArcPoint(t, maxDistance);
    51.         }
    52.  
    53.         return arcArray;
    54.     }
    55.  
    56.     Vector3 CalculateArcPoint(float t, float maxDistance)
    57.     {
    58.         float z = t * maxDistance;
    59.         float y = z * Mathf.Tan(radianAngle) - ((g * z * z) / (2 * velocity * velocity * Mathf.Cos(radianAngle) * Mathf.Cos(radianAngle)));
    60.         return new Vector3(0, y, z);
    61.     }
    I have this code but when I rotate a ball trajectory line position does not change because I don't know how to do it. How can I change trajectory's x position when I change ball's rotation?