I am making a physics engine in c# / XNA, I have three basic objects…
Sphere
Cube
Plane
that are all derived from
GameObject
I store all my objects in a list of GameObjects and I would like to loop through this list and be able to call a CheckCollision function that will go to the correct function for each pair of objects
eg
go is a Sphere,
go2 is a Sphere
if(CheckCollision(go, go2))
{
//do stuff
}
bool CheckCollision(Sphere one, Sphere two)
{
//Check Sphere to Sphere
}
bool CheckCollision(Sphere sphere, Plane plane)
{
//Check Sphere to Plane
}
and I would like it to just go to the correct function withour having to use if checks.
Thank you.
You could use virtual dispatch:
EDIT
Consider what happens when you have this:
Therefore, no type-checking
ifstatements are necessary.EDIT 2
See Eric Lippert’s answer at https://stackoverflow.com/a/2367981/385844; the first option — the visitor pattern — is essentially the approach outlined above. Eric’s other answer at https://stackoverflow.com/a/9069976/385844 also discusses this issue.