Skip to main content
gamedev.net
🔒 Locked

Saving array index?

Started by menyo Mar 28, 2011 at 6:37 PM 0 replies 600+ views
Original Post
menyo
menyo
So i think i have my collision script for my arkanoid/breakout game working. Except when it collides with 2 bricks, because of my foreach loop it picks the one that comes first in the list which is sometimes the wrong brick. Now i have to find some way to save the indexes of the bricks it hits and after the loop is finished then do the correct math. However i'm unsure how to save the index number for later or if there are otherways to get it work right. Heres the loop i have:


//brick collision
foreach (Brick brick in bricks)
{
if (brick.alive)
{
if (ballrectangle.Intersects(brick.Location))
{
//if ball moving moving up
if (ball.xSpeed == 0 && ball.ySpeed < 0)
{
ball.ySpeed *= -1;
brick.alive = false;
break;
}
//if ball moving down (Impossible to hit a brick right now)
else if (ball.xSpeed == 0 && ball.ySpeed > 0)
{
ball.ySpeed *= -1;
brick.alive = false;
break;
}

//if ball moving right and down
else if (ball.xSpeed > 0 && ball.ySpeed > 0)
{
float left = Math.Abs (brick.Location.Left - ballrectangle.Right) / Math.Abs(ball.xSpeed);
float top = Math.Abs(brick.Location.Top - ballrectangle.Bottom) / Math.Abs(ball.ySpeed);

if (left < top)
{
ball.xSpeed *= -1;
ball.Position.X = brick.Location.Left - ballgraphic.Width;
}
else
{
ball.ySpeed *= -1;
ball.Position.Y = brick.Location.Top - ballgraphic.Height;
}
brick.alive = false;
break;
}

//if ball moving right and up
else if (ball.xSpeed > 0 && ball.ySpeed < 0)
{
float left = Math.Abs(brick.Location.Left - ballrectangle.Right) / Math.Abs(ball.xSpeed);
float bottom = Math.Abs(brick.Location.Bottom - ballrectangle.Top) / Math.Abs(ball.ySpeed);

if (left < bottom)
{
ball.xSpeed *= -1;
ball.Position.X = brick.Location.Left - ballgraphic.Width;
}
else
{
ball.ySpeed *= -1;
ball.Position.Y = brick.Location.Bottom;
}
brick.alive = false;
break;
}

//if ball moving left and down
else if (ball.xSpeed < 0 && ball.ySpeed > 0)
{
float right = Math.Abs(brick.Location.Right - ballrectangle.Left) / Math.Abs(ball.xSpeed);
float top = Math.Abs(brick.Location.Top - ballrectangle.Bottom) / Math.Abs(ball.ySpeed);

if (right < top)
{
ball.xSpeed *= -1;
ball.Position.X = brick.Location.Right;
}
else
{
ball.ySpeed *= -1;
ball.Position.Y = brick.Location.Top - ballgraphic.Height;
}
brick.alive = false;
break;
}

//if ball moving left and up
else if (ball.xSpeed < 0 && ball.ySpeed < 0)
{
float right = Math.Abs(brick.Location.Right - ballrectangle.Left) / Math.Abs(ball.xSpeed);
float bottom = Math.Abs(brick.Location.Bottom - ballrectangle.Top) / Math.Abs(ball.ySpeed);
if (right < bottom)
{
ball.xSpeed *= -1;
ball.Position.X = brick.Location.Right;
}
else
{
ball.ySpeed *= -1;
ball.Position.Y = brick.Location.Bottom;
}
brick.alive = false;
break;
}
}
}
}

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.