We closed this forum 18 June 2010. It has served us well since 2005 as the ALPHA forum did before it from 2002 to 2005. New discussions are ongoing at the new URL http://forum.processing.org. You'll need to sign up and get a new user account. We're sorry about that inconvenience, but we think it's better in the long run. The content on this forum will remain online.
IndexProgramming Questions & HelpSyntax Questions › Dynamic casting or some other method
Page Index Toggle Pages: 1
Dynamic casting or some other method? (Read 463 times)
Dynamic casting or some other method?
Mar 14th, 2010, 7:11am
 
Hi, I'm trying to do something quite complicated and I'm not sure the best way to make it happen - I'm a Java novice, trying to port some Director code across.

What I have is a fairly complicated Physics engine, where every element is an instance of a PhysObject class. So for example I'll have PhysBall, PhysLineSegment, PhysPolygon etc. What I want to do is to give each instance a method mCollision(tObj) that calculates whether there's a collision between two objects. Now, of course, each object type collides differently, so my plan was to do this

Class PhysObject {
// *****other code****
Collision mCollision(PhysObject tObj) {
// cast to the appropriate subclass and send to the correct function
 if (tObj instanceof PhysBall) {
   return mCollisionWith((PhysBall) tObj)
 } else if (tObj instanceof PhysLineSegment) {
   return mCollisionWith((PhysLineSegment) tObj)
 }
 return new Collision()
}
}

Class PhysBall {
// *****other code****
// now pick up the mcollisionWith function and run it here
Collision mCollisionWith(PhysBall tObj) {
// code here for this collision type
}
Collision mCollision(PhysLineSegment tObj) {
// code here for this collision type
}
}
etc.

This works fine when the hCollisionWith methods are in the PhysObject class. The message is passed to the appropriate version of the method. Unfortunately, when they're in the subclass as above, for some reason they never get called.

I suspect I'm just using the wrong paradigm altogether. Can anyone help put me straight with how this should be done? And I hope I've made the issue clear!

Thanks
Danny
Re: Dynamic casting or some other method?
Reply #1 - Mar 14th, 2010, 7:28am
 
Problem solved!

I needed to put dummy methods for all the various versions of the mCollisionWith method into the superclass. I thought I could use a catchall mCollisionWith(PhysObject), but it wasn't enough.

Back to your lives, citizens.

Danny
Re: Dynamic casting or some other method?
Reply #2 - Mar 15th, 2010, 1:43am
 
Hi Danny,
thanks for letting us know. It would be great to see some of our final physics-classes once they are finished! Looking forward to it,
Bejoscha
Page Index Toggle Pages: 1