Drawing projectile trajectory

I have been trying to draw the trajectory path of a launched object using a line render but the line never seems to match the actually path the object takes.

I’ve already spent hours watching physics tutorials and scouring the web for an answer, but nothing seems to work.

This is a 2D game, so all objects are 2D(if that matters). Also I use seconds for the time but instead fixedTimeStep.

Here is pic of the situation.


Here is code

    var launchPower : float = 20;
    function Update() {
    var projectile : GameObject = Instantiate(prefab1,transform.position,transform.rotation);
    projectile.rigidbody2D.velocity.x = launchPower;
    function DrawTraject(var velocity : float;){
    var line = this.gameObject.GetComponent(LineRenderer);
    for(var i = 0; i < 20; i++){
    //I multiply by Physics.fixedDelta time so it can units/FixedtimeStep
    line.SetPosition(i, Vector3(transform.position.x + (launchPower * Physics.fixedDeltaTime) * i, transform.position.y - (Physics.gravity.y * Physics.fixedDeltaTime) * (i*i) /2, 0);

Ok… let’s recreate the physics formula, however, if it turns out to be wrong off too much, it may be a better idea to move the projectile yourself.

Also, I assume for now that you have drag=0 - if not, we have to experiment a bit as drag can be inserted at different stages in the process…

I usually write C#, so excuse me if I produce syntax error on the way - I won’t test the code:

DrawTraject(projectile.transform.position, projectile.rigidbody2D.velocity);

function DrawTraject(var startPos : Vector2, var startVelocity : Vector2;){

	var verts = 20;
	var line = this.gameObject.GetComponent(LineRenderer);

	var pos:Vector2 = startPos;
	var vel:Vector2 = startVelocity;
	var grav:Vector2 = Vector2(Physics.gravity.x, Physics.gravity.y);
	for(var i = 0; i < verts; i++)
		line.SetPosition(i, Vector3(pos.x, pos.y, 0));
		vel = vel + grav * Physics.fixedDeltaTime;
		pos = pos + vel * Physics.fixedDeltaTime;


It’s difficult to tell from your example code but have you tried turning on the following property:

line.useWorldSpace = true;

Without that property enabled the line is rendered relative to the game objects position.

You have to square time as well as i and it’s easier to use vectors for the math.

float t = Time.fixedDeltaTime;
Vector3 Pi = transform.position + new Vector3(launchPower,0,0)*t*i + new Vector3(0,-Physics.gravity,0)*.5*t*t*i*i;
Pi.z = desiredZ;
line.SetPosition(i, Pi);

This is the script created by me i hope this will be helpfull

Hi @ninjaboynaru, Do you resolve this issue. I got same issue like you. I replaced with rigidbody2d by rigidbody and it worked perfectly. I don’t know what is wrong with rigidbody2d