Search code examples
c#unity-game-engineprojectile

Need help making a sphere move in parabola as part of a projectile simulator?


Hi I'm currently working on a school computer science project for which I have decided to make a simple projectile simulator, where the user just provides the initial launch speed, the launch angle, and gravity. So far I've tried to make a script that uses these values to calculate a trajectory pattern and change the y and z position of a sphere across a plane over time.

public class SphereJump : MonoBehaviour{

    public float gravity = 9.8f;
    public float InitialSpeed = 10.0f;
    public float LaunchAngle = 45.0f;

    public Transform Sphere;

    void Start () {

        float InitialX = Mathf.Sin(LaunchAngle) * InitialSpeed;
        float InitialY = Mathf.Cos(LaunchAngle) * InitialSpeed;

        float Range = Mathf.Sin(2*LaunchAngle)*Mathf.Pow(InitialSpeed,2)/gravity;

        float MaxHeight = Mathf.Sin(LaunchAngle) * Mathf.Pow(InitialSpeed, 2) / 2 * gravity;

        float FlightTime = Range / InitialX;

        float ElapsedTime = 0;

        while (ElapsedTime < FlightTime)
        {
            float NewPositionX = transform.position.z+InitialX*ElapsedTime;
            float NewPositionY = transform.position.y +InitialY -gravity / 2*ElapsedTime;

            Sphere.Translate(0f, NewPositionY, NewPositionX);

            ElapsedTime += Time.deltaTime;
        }
    }

}

Being completely new to Unity, in my head this should mathematically work, however when I run the game either nothing happens or the sphere object disappears. At the start it's position is (1, 0.5, 1) - which is just 0.5 above the plane it's sitting on - and as far as I'm aware the script is correctly attached. A warning also comes up saying "Due to floating point precision limitations...". Would using Vector3 help? Have I confused the script entirely?


Solution

  • this should go in an Update() you can add that method yourself and move the code.

    as for your second question:

    Vector 3 is a coordinate system for a point position in 3d space, X,Y and Z! you will need a z coordinate to denote depth, or unity dosnt know where to place your object

    so:

    Vector3 newPos= new Vector3(x,y,z);
    

    z can remain constant if you dont want distance from the camera to vary.

    Vector3 newPos= new Vector3(transform.position.z+InitialX*ElapsedTime,transform.position.y +InitialY -gravity / 2*ElapsedTime,z);
    

    however,

    in unity there is a component called rigidbody. attaching this to your object will add gravity and physics.

    you can then get the rigidbody in script:

    RigidBody body = this.GameObject.GetComponent<RigidBody>();

    then you can do:

    body.AddForce(position,direction,force);
    

    or body.gravity=3;

    or several other adjustments to incorperate your physics challenge.