I am making simple top down game. There are 8 possible directions of car so I want to assign proper image to display for each direction.
My idea: Pass 8 images to Car class (like an array of bitmaps) In the Position_X and Position_Y properties I could in the Set accessor determine which direction is now to be displayed and select the proper image. Would it make sense?
class Car
{
Bitmap ImageToDisplay;
Bitmap left;
Bitmap right;
...
public Car(Bitmap [] dirImages)
{
left=dirImages[0];
right=dirImages[1];
..etc
}
public int POSITION_X
{
开发者_StackOverflow中文版 set
{
if (POSITION_X>value)
ImageToDisplay=left;
else ImageToDisplay=right;
}
}
}
I would argue for separation of concerns.
If this was your complete Car class this would be OK, but I assume your Car class will do some more work.
Inspired from my latest adventures with WPF and databinding I would propose that the Car class exposes a property Direction
, preferably with an enum
describing your 8 directions. Then you have a separate converter class that converts the Direction
to a bitmap.
By breaking out the actual bitmap selection from the Car class you separate the logic (calculation of the direction) with presentation (selection of the appropriate bitmap).
This way you can reuse the Direction
properties for other purposes, like calculation where the car moves and when figuring out how user input should affect the car movement.
There is nothing technically wrong with your code, but there is a big risk that you end up with a huge car class that does to many things at once. A warning sign might be that when your POSITION_X
setter besides updating ImageToDisplay
updates five other properties too.
I would have a separate function that is called whenever the rotation of the object changes, and that function would know, based on the objects rotation, which image should be the "active" image, and how to update the objects display and private "currentImage" property.
精彩评论