Home > Software design >  Add force to ball when hit by other ball
Add force to ball when hit by other ball

Time:05-04

I'm creating a pool game my problem now is adding a force to ball when it get hits by other ball. Is it ok I'll just adjust the mass of other ball? enter image description here

CodePudding user response:

There is many ways of doing that, which you can see by searching the Rigidbody Methods in Unity Docs.

One of them, and the one that i use is the AddForce() method because of the ease. Check the official docs for more info: https://docs.unity3d.com/ScriptReference/Rigidbody.AddForce.html

I would suggest that you calculate the direction subtracting de position of both balls in the moment of impact.

About the mass, yes, you can change the mass of the other balls, but i recommend that you study a little bit more of Unity's Physics system in order to achieve your goals, maybe your problem isn't in the balls mass.

CodePudding user response:

Unity has better ways to do this. But I'm assuming you want to find the basics of physics. This explains the power angle obtained by subtracting the position of the hit ball from the striking ball. We normalize it to the unit and you can define the amount of force statically or dynamically.

public float force = 10f;
private void OnCollisionEnter(Collision collision)
{
    if (!collision.transform.CompareTag("Ball")) return;

    var direction = (transform.position - collision.transform.position).normalized;
    
    collision.transform.GetComponent<Rigidbody>().AddForce(direction*force);
}

To dynamize the force, just multiply the speed of the first ball in it. rigidbody.velocity.magnitude does this, but if rigidbody is used, the above steps are performed automatically and very accurately.

  • Related