質問

I have been working on a Java game for a few months now and I've run into a problem.

My Player walks around in an Environment, which is comprised of tiles that all have their own CollisionBox. Put simply: when the Player's CollisionBox collides with another CollisionBox (like that of a box or something), then the Player can't move. That part is taken care of.

I'm trying to introduce InteractiveTiles, in which the Player will cause something to happen if it collides with a specific CollisionBox, such as stairs or a door. Specifically, I want to be able to transition to a new Environment if specific *InteractiveTile*s are hit.

I have the functionality to transition and redraw collision maps, but I don't know how to make that collision event tell the Environment (which is not conveniently in the hierarchy of the code to the collision event).

I am familiar with the Observer Pattern, in which the Environment could "hear" this collision, but I am not really sure how it would be implemented here, or even if that's the right design pattern for this situation!

Even more simply...

When Player.IsCollidingWithDoorLeadingToNewEnvironment(newEnvironment) is called, Environment.TransitionToNewEnvironment(newEnvironment) should be called, but they are far apart from each other in the code structure.

More broadly: how can I send messages between two classes without layers upon layers of method/constructor injection?

役に立ちましたか?

解決

Have you heard of the Model-View-Controller model? It's nothing fancy but maybe it could help. Basically your program will have three parts:

  1. Model - These are all of the italicized words in your question, that represent the parts of the program that interact to comprise it.
  2. View - Display; not as relevant here, it's just like how things are drawn onto the screen
  3. Controller - This is what I think will help you. This is a class that runs the whole show. This class controls all of the parts generated in the Model component of the program and this is what allows them to communicate. I imagine the Environment class may be good for this in your case.

Your controller class may contain arrays/ArrayLists that contain all of the parts generated during the game, like the CollisionBoxes. Each CollisionBox (I'm just using this as an example) could have an instance variable (call it id maybe) that represents its position in the array (it could be as simple as the index, an int). When two Boxes collide, you could call a method in the controller class that takes the two ids, and conveniently these ids would refer to where they are in the array. Of course, you could use other data structures, but I hope this gives you the basic idea.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top