Reputation: 39
TLDR: I need a variable that can take in an object from either of 2 classes.
I'm working on a Java 2D game, still getting the basics to work and here I have a problem: in the class Actor, in the constructor, the actor generates its hitbox (4 XY coordinates object) and then adds that hitbox to a list of things that need to check for collisions.
But now that I got all this working, I made a new class, Platform, so that my character can walk on something else than the defiled corpses of it's enemies. But in the Rect constructor, I have a variable (Parent
) that sets itself to the object that called the constructor (with itself in parameter) so I would get hitbox.parent() = player for example.
But since the Platform objects are from another class (that I don't really want to inherit from the Actor class) how can I make it so that Rect and give itself a parent of different type ?
The class as it is now
package misc;
import item.Platform;
import npc.Actor;
public class Rect {
int x,y,wdt,hgt;
public Rect(Actor a){
x = a.x;
y = a.y;
wdt = a.wdt;
hgt = a.hgt;
}
public Rect(Platform p){
parent = p;
x =p.x;
y =p.y;
wdt =p.wdt;
hgt =p.hgt;
}
}
And here is the place where I have trouble calling it
private static void collision(Rect r1,Rect r2){
if (r1.y -r2.y <= r2.hgt && r1.y -r2.y >= -r2.hgt){
r1.parent.yCol = true;
}else{
r1.parent.yCol = false;
}
if (r1.x -r2.x <= r2.wdt && r1.x -r2.x >= -r2.wdt){
r1.parent.xCol = true;
}else{
r1.parent.xCol = false;
}
}
Upvotes: 0
Views: 62
Reputation: 925
In addition to inheritance, you could also use an interface based approach.
public interface GameRect {
int getX();
int getY();
int getHeight();
int getWidth();
}
public class Actor implements GameRect {
// implementation
}
public class Platform implements GameRect {
// implementation
}
public class Rect {
// implementation
private GameRect parent;
// constructor works for all classes that implement GameRect interface
public Rect(GameRect gr) {
parent = gr;
x = gr.getX();
y = gr.getY();
// etc
}
}
The problem with a solution like this is that you need to cast back to the original type (Actor, and Platform respectively) every time you want to call class methods on the parent
objects that are not GameRect interface methods.
Upvotes: 1
Reputation: 525
You need to use Inheritance, which is one of the most important aspects of Object Oriented Programming. You need to do some reading on it so you understand how it works and how to use it: https://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html
Upvotes: 1