Reputation: 3
I am making a game/game engine and encountered the following problem: i have a player that has a "checkCollision(Wall w)" method. it takes in a very simple object wall, which has some data and checks the collision with it. this works fine. but now i have this "door" object, which inherited the object "wall". this object is mostly the same but has some extra functionality. now haw can i call functions from this door object? so the door looks like: class Door : Wall {}
The function checkCollsion: takes a wall as type in.: player.checkCollision(Wall w)
the i pass for example Door d1
in the function: player.checkCollision(d1)
.
now i can check the collison, and it works fine, but how do i call a function from the door passed in as wall from inside the checkCollision function? ps each object has a tag, and a walls tag = "wall" and a doors tag = "door".
so i the checkCollision:
public void checkCollision(Wall w){
if(w.tag =="wall"){
//collision checking
}else if(w.tag == "door"){
//collision checking
//this is a function only "door" has:
w.SomeMethodOnlyDoorHasAndWallLacks();
}
}
how can i call this function?
thanks in advance,
cody
Upvotes: 0
Views: 64
Reputation: 236318
I would not inherit door from wall. Create some base object or interface and inherit both wall and door from it:
public abstract class EnvironmentObject
{
// tag
public bool CheckCollision()
{
// collision checking
}
public abstract void Act();
}
Now when implementing Act
in wall object you can leave it empty. In door object you can add some actions. And collision checking will look like
var objects = new EnvironmentObject[] { new Wall(), new Door() };
foreach(var obj in objects)
if (obj.CheckCollision())
obj.Act();
Upvotes: 2
Reputation: 2761
Variant 1:
public void checkCollision(Wall w){
if(w is Door){
//collision checking
//this is a function only "door" has:
(w as Door).SomeMethodOnlyDoorHasAndWallLacks();
}else
// wall
}
}
Variant 2:
Define method for collision check in base class:
class Wall
{
public virtual void CheckCollision(some arguments)
{
// default collision check code
}
}
class Door : Wall
{
public override void CheckCollision(some arguments)
{
// overriden collision check code
}
}
Upvotes: 0