Hello guys. I’m trying to draw a realtime line of the trajectory of a cannonball in 3 dimensions. It works, however, the line itself does not rotate correctly. It shows the trajectory of a cannonball, fired from the front of a ship, yet, the line only has the original rotation of the gameObject it starts from.
Can you guys look at this, and perhaps give me som tips/tricks on how to make this work the way i intend it to work?
Thanks in advance.
Here is the code.
public Rigidbody projectile;
public Vector3 muzzleVelocity;
public float power;
public GUIText powerGUI;
void Update()
{
powerGUI.text = muzzleVelocity.ToString();
if(Input.GetKey(KeyCode.Space))
{
muzzleVelocity = muzzleVelocity + power * Vector3.forward;
Trajectory(gameObject.transform.position,muzzleVelocity,gameObject.transform.rotation, Vector3.down);
}
if (Input.GetKeyUp(KeyCode.Space))
{
Rigidbody clone;
clone = Instantiate(projectile, transform.position, transform.rotation) as Rigidbody;
clone.velocity = transform.TransformDirection(muzzleVelocity);
muzzleVelocity = GameObject.Find("Ship").rigidbody.velocity + Vector3.forward * 10;
}
}
//Cannonball trajectory calculation and render
void Trajectory(Vector3 initialPosition, Vector3 initialVelocity, Quaternion initialRotation, Vector3 gravity)
{
int trajectoryLineSteps = 100;
float timeDelta = 1.0f / initialVelocity.magnitude;
LineRenderer lineRenderer = GetComponent<LineRenderer>();
lineRenderer.SetVertexCount(trajectoryLineSteps);
Vector3 position = initialPosition;
Vector3 velocity = initialVelocity;
Quaternion rotation = initialRotation;
for (int i = 0; i < trajectoryLineSteps; i++)
{
lineRenderer.SetPosition(i,position);
lineRenderer.transform.Rotate(Vector3.up,Vector3.Angle(Vector3.zero,transform.position));
position += velocity * timeDelta + 0.5f * gravity * timeDelta * timeDelta;
velocity += gravity * timeDelta;
}
}
}