mardi 24 février 2015

Winforms Space Invaders game bug with Ticker

I´m writing a Space Invaders game in which I have 2 Tickers (invoked in 10 and 75ms intervals). For this purpose the 10ms Ticker is crucial. The ticker indirectly calls the method you see below. This method is responsible for the moving of the Invaders/ Aliens.


They first move rightwards till they reach the right border (ClientRectangle - 100), then they SHOULD move 30 pixels down and switch their currentWay leftwards. If they reach the left border (ClientRectangle + 100) they should also move 30 pixels down and again switch their currentWay. The right and left moving is no problem and the down movement also works, BUT sometimes they move down 2 or 3 times (2 or 3 * 30 pixels).


I can´t figure out the problem. I guess that the ticker calls the method so often that the new position isn´t yet calculated.



private void MoveInvaders()
{
bool downLeft = false;
bool downRight = false;

if (movedDown)
{
//rect = ClientRectangle of the Form
//I´m using LINQ for some collision detection
//The surface is the representation of the Invader as a Rectangle

downRight = (from inv in invaders
where (inv.Surface.X + inv.Surface.Width) < rect.right - 100
select inv).ToList().Count > 0;

if (!downRight)
{
downLeft = (from inv in invaders
where inv.Surface.X > rect.left + 100
select inv).ToList().Count > 0;
}

if (downRight || downLeft)
{
movedDown = false;
downLeft = false;
downRight = false;
}

}
else
{

downRight = (from inv in invaders
where (inv.Surface.X + inv.Surface.Width) >= rect.right - 100
select inv).ToList().Count > 0;

if (!downRight)
{
downLeft = (from inv in invaders
where inv.Surface.X <= rect.left + 100
select inv).ToList().Count > 0;
}
}

foreach (Invader invader in invaders)
{
if (!movedDown)
{
if (downRight)
{
invader.Move(Way.Down); //Their old Point.Y += 30
currentWay = Way.Left;
}
else if (downLeft)
{
invader.Move(Way.Down);
currentWay = Way.Right;
}
}

invader.Move(currentWay); //old Point.X += 1
}

if (!movedDown && (downLeft || downRight))
{
movedDown = true;
}
}

Aucun commentaire:

Enregistrer un commentaire