Muhammad Haseeb
Muhammad Haseeb

Reputation: 1341

How can i give soccer ball a trajectory?

I am a beginner and trying to make penalty shooter Game in unity.. I have just setup the scene and just trying to shoot the ball towards the goal post. When i shoot the ball it goes toward the goal but does not come down, because i am shooting it through the script and its gravity is off and kinematic is on.

Currently i have the following script:

void Start () {
    startTime = Time.time;
    rb.GetComponent<Rigidbody>();
}
    
void Update () {
    transform.position -= fakevel * Time.deltaTime;
    transform.position += fakeGravity * Time.deltaTime;
    fakevel *= 0.999f ;
}

void OnTriggerEnter( Collider other ) {
    fakevel = new Vector3(0.01f, 0, 0) * 2000f;
    fakeGravity = new Vector3 (0 ,0.01f, 0)* 200f;
    y = -45.68312f;
}

I have tried enabling the gravity and disabling the kinematic at some specific position but i does so the gravity just pull it down at that position and it does not look realistic. Some screen shoots are attached. enter image description here

Please help me in setting trajectory of the ball and stopping it when it collides with the goalpost,

Upvotes: -1

Views: 2744

Answers (2)

Andrew Labreck
Andrew Labreck

Reputation: 41

Seeing how it does work, just doesn't give the effect you want, you can either spend several hours fine tuning it, or like xyLe_ stated, use the built in physics. Using the built-in physics isn't a bad thing, you just gotta be smart with it. You can add a bouncy physics material also, which will help give the ball a well, ball feel.

Upvotes: 1

nyro_0
nyro_0

Reputation: 1135

I would suggest you use a non-kinematic rigidbody on your ball and add a force to it when you shoot it: GetComponent<Rigidbody>().AddForce(forceVector3, ForceMode.Impulse) (this is just an example, you should avoid calling GetComponent on a frequent basis, you are better off calling it for the rigidbody component once on Start and store it in a private variable)

This way Unity's physics engine can handle gravity and the balls' velocity over time. To modify the trajectory you can play around with the properties of the balls' rigidbody component.

If you want to have more control over the velocity, you can also set the rigidbody's velocity directly in the FixedUpdate() (which is called right before each physics update). When doing so, you have to consider that velocity is measured in m/s and the physics engine handles sub-steps for you (I am assuming that FixedUpdate() is called more than once per second), meaning you do not have to multiply your velocity with some delta time (but I am not 100% sure about this right now).

Upvotes: 1

Related Questions