Line renderer projectile trajectory in 3D world

Hello,

I’m having a trouble with a script to calculate de ball trajectory of the cannons in my game.

I have a root object, inside him are the cannon mesh and a empty transform called point that I use for position and rotation when instantiate the ball on shoots.

I use a linerender on that point and a control script on the root to calculate the trajectory and shoot the cannon when needed.

My problem is the trajectory calculation, I already successful calculate it and it works fine, but it is a script that only 100% if my game was 2D, but the game is 3D.

So when I rotate the root in the Y axis the line renderer rotates too, but its not in the right location anymore, some codes tests make it off-set from the point’s origin and other makes the curvature of the parabola changes too without changing the power of the shoot and not the right forward from point.

The actual code:

        Vector3 vel = point.forward * power;
        //Vector3 vel = point.TransformDirection(new Vector3(0, 0, power));
        Vector3 pVelocity = vel / 1;

        float velocity = Mathf.Sqrt((pVelocity.y * pVelocity.y) + (pVelocity.z * pVelocity.z));
        float angle = Mathf.Atan2(pVelocity.y, pVelocity.z);
        float fTime = 0;

        lineRenDebug.positionCount = numOfTrajectoryPoints;

        for (int i = 0; i < numOfTrajectoryPoints; i++) {
            float dx = velocity * fTime * Mathf.Cos(angle);
            float dy = velocity * fTime * Mathf.Sin(angle) - (Physics2D.gravity.magnitude * fTime * fTime / 2.0f);

            Vector3 pos = new Vector3(0, dy, dx);
            //Vector3 pos = new Vector3(transPonta.position.x, dy, dx);

            //Vector3 finalPos = Vector3.Scale(point.forward, pos) + point.position;
            //Vector3 finalPos = point.TransformDirection(point.position + pos);
            Vector3 finalPos = point.position + pos;
            lineRenDebug.SetPosition(i, finalPos);

            fTime += 0.15f;

            if (finalPos.y < -2f) {
                lineRenDebug.positionCount = i;
                break;
            }
        }

The comments are some changes that I tried and not worked.

Someone can try to help me? Or a tip that something that I’m missing here.

Thanks.

Those things work a little different in three dimensions. When calculating the magnitude of the velocity vector, you’re only taking the y and z coordinates into account, but as soon as you rotate your cannon, you need x as well. Take a look at Vector3.magnitude, which is an already implemented method to get the magnitude of a vector.