hello, in my game i am trying to handle the collisions manually.
at this point i have on each gameObject with a collider a script with onCollisionEnter(){}
in this function it passes to my gamePhysics script, the object number of this.gameObject and other.gameobject. so that i can resolve all collsiions in my gamePhysics script…
in my game physics script i have a function
CollisionDetected(int ball1Number, int ball2Number)
{
but how do i store these so that i may compare other results. im thinking to stopre them in the same variable that can store 2 ints…
and then compare if another collision pair is a = b, b = a, dont collide;
}
Write your own class with a comparison function:
public class CollisionPair : IEquatable<CollisionPair> {
public GameObject ball1 { get; private set; }
public GameObject ball2 { get; private set; }
public CollisionPair(GameObject ball1, GameObject ball2) {
this.ball1 = ball1;
this.ball2 = ball2;
}
public override bool Equals(CollisionPair other) {
return (this.ball1 == other.ball1 && this.ball2 == other.ball2) ||
(this.ball2 == other.ball1 && this.ball1 == other.ball2);
}
}
Then in your OnCollisionEnter you can make a new one:
void OnCollisionEnter(Collision col) {
CollisionPair pair = new CollisionPair(gameObject, col.gameObject);
GamePhysics.Instance.CollisionDetected(pair);
}
Then you can check if you’ve already processed this particular collision using the Equals method. You probably want to override HashCode too if you’re going to use these things in a collection like a HashSet.
1 Like
can u please explain more about the override hashCode… the code that u posted i needed to add System. before the IEquatable to make it work and i needed to take out the Override function Equals…
does this make a difference?
cuz i read that its important to overide the hash code for performance or something like that… not sure i understood too well…
Equals and Hashcode are important for if you want to put the object into a collection like HashSet or as a key in a Dictionary. The collection will use Hashcode and equals to detect if two objects are the same. That will prevent duplicate keys in a Dictionary or duplicate values in a HashSet.
So your GamePhysics calss could use a HashSet for example to keep track of which collisions it has already processed so it doesn’t process a collision twice.
1 Like