Sign in to follow this  
Franks

Behavior between entites and tiles

Recommended Posts

Franks    128

Hi,

I make a game like Mario where there are differents types of entities and tiles. Each entity has his own behavior when it collide with a tile. For exemple, when a player walks on Spike he dies. But a certain type of enemy can walk on Spike.

Is there a good way to write this in OOP ? Without cast, without breaking OCP principle and not having to write every behavior in every objects. Is there a design pattern ?

Share this post


Link to post
Share on other sites
Nypyren    12074
It's a multiple dispatch problem. You shouldn't overthink it. You can either write a multiple dispatch table, or just do it the simple way:

Mario: "Hey tile, I collided with your top edge."
Spike: "I don't care."
Mario: "Are you a spike, by any chance?"
Spike: "Yes."
Mario: "Ouch!"

Turtle: "Hey tile, I collided with your top edge."
Spike: "I don't care."
Turtle: "Well, neither do I." Edited by Nypyren

Share this post


Link to post
Share on other sites
Franks    128

It's a multiple dispatch problem. You shouldn't overthink it. You can either write a multiple dispatch table, or just do it the simple way:

Mario: "Hey tile, I collided with your top edge."
Spike: "I don't care."
Mario: "Are you a spike, by any chance?"
Spike: "Yes."
Mario: "Ouch!"

Turtle: "Hey tile, I collided with your top edge."
Spike: "I don't care."
Turtle: "Well, neither do I."

 

This is what I did. When Mario walks, I check the tiles around him and I cast the tile to know the type. But is it a good practice ... If I have 20 tiles, do I need to create 20 if statement for every entity or tile ? And if I add a new tile or enemy, I need to find where I need to add an if statement ...

Maybe you right, this is the right way and I shouldn't overthink it.

Share this post


Link to post
Share on other sites
Nypyren    12074
It will depend on how much you share between different entities.

For example, with a multiple-dispatch table, if the table gets unreasonably large, you probably want to start thinking about categorizing your entity/tile types differently. For example Mario can walk on top of blocks, coin blocks, powerup blocks, etc. You could give the block definition a "what happens when player walks on top of me" field, instead of trying to define all of the properties of every combination in a single place.

If you can categorize each bit of behavior differently, and most importantly *separately*, it should help you keep your code cleaner. Edited by Nypyren

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this