Behavior between entites and tiles

Started by
2 comments, last by Nypyren 6 years, 10 months ago

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 ?

Advertisement
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."

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.

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.

This topic is closed to new replies.

Advertisement