I’m running a simulation of a gas, and in this simulation two particles are moving and will inevitably collide.
I’m struggling to figure out how to get the two particles (which can be of different mass) to correctly calculate their new trajectory and speed after bouncing off each other.
I’m afraid I can’t use a physics material, as this is for a school project and that would be letting unity do all the work for me.
If this is a school project, surely it’s asking you to apply something you’ve already been taught so what part (specificially) don’t you understand?
How to use Unity physics to detect a collision?
How to get the details of the collision?
Do you want this to be an inelastic or elastic collision?
The equations to change the momentum after collision?
A physics material only configures the friction and bounce (restitution) and doesn’t control the reflected angle etc so are you also calculating that?
Assuming a simple Sphere/Sphere contact then Unity will give you a Collision that reports the contact point(s) and a collision normal on the surface of the sphere so you can reflect the velocity around that. The thing you’ll need to do is adjust the Rigidbody velocity accordingly i.e. reflect the velocity around the collision normal then adjust its magnitude to maintain a speed.
In Unity, you’ll need to use a Rigidbody using Continuous Collision Detection so they never overlap and the contact point is on the surface of those spheres. If you use Discrete then you’ll get some overlap which won’t help your simulation.
If however you’re not using physics at all (I think you are because you’ve only mentioned that you don’t want to use a collision material) then does the list of don’t knows include how to perform collision detection etc?
The script below will make an object bounce around. It takes care of the quirky Unity behavior like having to use the previous rigidbody velocity and not the current velocity when a collision occurs. You probably wouldn’t have figured that out yourself. But see if you can figure out how to modify the velocity for objects with different masses.
using UnityEngine;
public class BounceAround : MonoBehaviour
{
Rigidbody rb;
Vector3 oldVelocity;
void Start()
{
rb=GetComponent<Rigidbody>();
Vector3 v=Random.insideUnitCircle*8;
rb.velocity=v; // give the object a little push
}
void FixedUpdate()
{
oldVelocity=rb.velocity;
}
void OnCollisionEnter(Collision collision)
{
Vector3 v=Vector3.Reflect(oldVelocity,collision.contacts[0].normal);
rb.velocity=v;
}
}