I have an “Extension” class for handling general functions that’s designed to be used dynamically – that is, I want to be able to use it with many different classes and variables (kind of like how you would use something like the Math class). But I’ve encountered a little problem that I can’t seem to figure out (I’ve looked at quite a few forums and websites, but no luck).
Here’s the function from my Extension class:
public void setPlayerFriction(Object objectType, double hspeed, double vspeed){
objectType obj = new objectType();
if(obj.hspeed >= GameWindow.friction){
obj.hspeed -= GameWindow.friction;
}else if(obj.hspeed <= -GameWindow.friction){
obj.hspeed += GameWindow.friction;
}else{
obj.hspeed = 0;
}
if(obj.vspeed >= GameWindow.friction){
obj.vspeed -= GameWindow.friction;
}else if(obj.vspeed <= -GameWindow.friction){
obj.vspeed += GameWindow.friction;
}else{
obj.vspeed = 0;
}
}
And the function’s use in my Player class:
public void runPhysicsEngine(){
Extensions ext = new Extensions();
ext.setPlayerFriction(this,hspeed,vspeed);
}
Obviously doing something like obj.var -= GameWindow.friction;, where obj and var are arguments of a method, isn’t the right way to do what I want to do – it just returns the unresolved type error. So what is the right way? How do I access a variable from a dynamic class name?
I think having an
abstractclass for yourobjectTypewith appropriategetter/settermethods might help. For example:You can then have concrete implementation of your
ObjectTypeclasses thatextendthisParentObjectclass. And you would change yoursetPlayerFriction()method as follows:And to this method, you would basically be sending references of classes that have actually extended your
ParentObjectclass. For example: