Ssiro
Ssiro

Reputation: 135

Unity3D: Get Velocity after collision

I'm making a billiard game and I have two questions:

How do I find the velocity of two balls when they collide with each other and how do I apply it to both balls ?

I already know the angles that they're gonna move, I just need to find the velocity that they'll move in those directions.

I was never good at physics/physics programming so I would appreciate any help given! Btw, my game is in 3D.

Thank you for your time!

Edit: What I'm trying to do is make the movement direction match the direction that I'm calculating using this script:

if (Physics.Raycast(ray, out hit, Mathf.Infinity, lmm))
{
    location = new Vector3(hit.point.x, 1.64516f, hit.point.z);
}

if (Physics.SphereCast(transform.position, 0.77f, location - transform.position, out hitz, Mathf.Infinity, lmm2))
{
    if (hitz.collider.tag == "Ball")
    {
        Vector3 start = hitz.point;
        end = start + (-hitz.normal * 4);
        lineRenderer2.SetPosition(1, end);
    }

}

Upvotes: 0

Views: 4269

Answers (2)

py13579
py13579

Reputation: 56

You can calculate the new velocities by applying an impulse to each ball. We can apply Newton's Third law to do so. PseudoCode:

    RelativeVelocity = ball1.velocity - ball2.velocity;
    Normal = ball1.position - ball2.position;
    float dot = relativeVelocity*Normal;
    dot*= ball1.mass + ball2.mass;
    Normal*=dot;
    ball1.velocity += Normal/ball1.mass;
    ball2.velocity -= Normal/ball2.mass;

This however does not take into account friction between the two balls nor their angular momentum.

Upvotes: 2

Agustin0987
Agustin0987

Reputation: 601

If I understand correctly, what you are trying to do is to apply the speed of "Ball A" as a force to "Ball B", and vice versa as well. If that is the case I would suggest something like this:

Attach this script to all the balls:

public class BallCollisionScript : MonoBehaviour 
{   
    public Rigidbody Rigid_Body;

    void Start()
    {
        Rigid_Body = this.GetComponent<Rigidbody>();
    }

    void OnCollisionEnter(Collision collision) 
    {
        if (collision.gameObject.tag.Equals("Ball"))
        {
            BallScript otherBall = collision.gameObject.GetComponent<BallScript>();
            Rigid_Body.AddForce(otherBall.Rigid_Body.velocity);
        }
    }
}

Make sure that all balls are tagged with "Ball".

Upvotes: 0

Related Questions