Frage

Here's my bit of code, it moves the Play Field left to right moving down one each time it hits the sides.

    private void moveMonsterPlayField()
    {
        if (monsterPlayField.DirectionRight)
        {
            monsterPlayField.X++;
            if (monsterPlayField.X + monsterPlayField.Width >= this.width)
            {
                monsterPlayField.DirectionRight = false;
                monsterPlayField.Y++;
            }
        }

        else 
        {
            monsterPlayField.X--;
            if (monsterPlayField.X == 0)
            {
                monsterPlayField.DirectionRight = true;
                monsterPlayField.Y++;
            }
        }



    }

But it's a bit verbose.

Instead I'd like to do something like:

    private void moveMonsterPlayField()
    {
       monsterPlayField.X += monsterPlayField.DirectionRight * 1 //where DirectionRight resolves to 1 or -1

       if (monsterPlayField.X + monsterPlayField.Width >= this.width || monsterPlayField.X == 0)
       {
           monsterPlayField.DirectionRight = !monsterPlayField.DirectionRight;
           monsterPlayField.Y++;
       }



    }

is that possible?

War es hilfreich?

Lösung 2

Another alternative you might consider is to use two integer properties to represent the monster's current velocity instead, specifying the X and Y components:

int VelocityX;
int VelocityY;

Currently you would limit the values to -1, 0, and 1 (but you could specify higher velocities in the future).

Then your code to adjust the monster (X,Y) location would be:

monsterPlayField.X += monsterPlayField.VelocityX;
monsterPlayField.Y += monsterPlayField.VelocityY;

You'd still need to range-check the X and Y values after changing them.

Andere Tipps

You could use something like this:

monsterPlayField.X += monsterPlayField.DirectionRight ? 1 : -1;

In fact, this is just an if statement, with true and false result.

Other options:

  • You could add another property to your class calculating this.
  • Create a class, and override the conversion operator to bool and int, although I would stay away from that personally.

Another option is to use a Enum and assign values to enum members.

enum Direction
{
    Right = 1,
    Left = -1
}

You can then cast the enum in to their int values in your code.

private void moveMonsterPlayField()
{
   monsterPlayField.X += (int)monsterPlayField.Direction; // Direction is now of type Direction instead of bool

   if (monsterPlayField.X + monsterPlayField.Width >= this.width || monsterPlayField.X == 0)
   {
       monsterPlayField.Direction = (Direction)((int)monsterPlayField.Direction * -1); 
   }
}
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top