该程序有球,蝙蝠和矩形。我设法让球正确地与球棒碰撞,这没关系。问题在于矩形。
对于我迄今为止所尝试的矩形,它确实检测到来自顶侧和左侧的碰撞,但我正在努力获得与底部和右侧相同的效果。
关于我哪里出错的任何指示我都会非常感激。为清楚起见,我在下面提供了代码。此外,当球确实碰撞时,它向左上方反弹。
Graphics paper;
SolidBrush brush;
private Random randomNum;
Rectangle ball, bat, brick;
int x, y, yChange, xChange, batX;
public Form1()
{
InitializeComponent();
paper = picBox.CreateGraphics();
randomNum = new Random();
bat = new Rectangle();
brick = new Rectangle();
}
private void MoveBall()
{
timer1.Interval = randomNum.Next(80, 200);
timer1.Enabled = true;
x = x + xChange;
y = y + yChange;
if (x >= picBox.Width)
xChange = -xChange;
if (y >= picBox.Height)
yChange = -yChange;
if (x <= 0)
xChange = -xChange;
if (y <= 0)
yChange = -yChange;
}
private void DrawBall()
{
brush = new SolidBrush(Color.Red);
ball = new Rectangle(x, y, 14, 14);
paper.FillEllipse(brush, ball);
}
private void DrawBat()
{
int batXpos, batYpos;
batXpos = batX - 25; batYpos = picBox.Height - 40;
bat = new Rectangle(batXpos, batYpos, 100, 20);
brush = new SolidBrush(Color.Green);
paper.FillRectangle(brush, bat);
}
private void DrawBricks()
{
brick = new Rectangle(200, 100, 100, 50);
brush = new SolidBrush(Color.Pink);
paper.FillRectangle(brush, brick);
}
private void CheckCollision()
{
int ballTop, ballRight, ballDown, ballLeft;
ballTop = ball.Y + 7; ballDown = ball.Y + 14 + (ball.X + 7); //THESE WERE JUST SOME ATTEMPTS TO GET
ballRight = ball.X + 14 + (ball.Y + 7); ballLeft = ball.Y + 7; //LOCATION OF THE BALL AND BRICK X AND Y
//COORDS BUT STILL HAD PROBLEMS
int brickTL, brickTR, brickBL, brickBR;
brickTL = brick.X; brickTR = brick.X + 100;
brickBL = brick.Y + 50; brickBR = brick.X + 100 + (brick.Y + 50);
if (ball.IntersectsWith(bat)) //NO PROBLEMS HERE
{
yChange = -10;
}
if (ball.IntersectsWith(brick)) //WORKS FINE FOR DETECTION ON THE TOP SIDE
{
xChange = -5;
}
if (ball.IntersectsWith(brick)) //WORKS FINE FOR THE RIGHT SIDE
{
yChange = -5;
}
if ((ballTop >= brickBR) && (x < picBox.Width))
{
yChange = 5;
}
}
private void btnStart_Click(object sender, EventArgs e)
{
timer1.Interval = randomNum.Next(80, 200);
timer1.Enabled = true;
x = randomNum.Next(5, picBox.Width);
y = randomNum.Next(5, picBox.Height);
xChange = randomNum.Next(5, 15);
yChange = randomNum.Next(5, 15);
}
private void timer1_Tick(object sender, EventArgs e)
{
paper.Clear(Color.Gray);
DrawBall();
MoveBall();
DrawBat();
CheckCollision();
DrawBricks();
}
private void picBox_MouseMove(object sender, MouseEventArgs e)
{
batX = e.X;
}
答案 0 :(得分:0)
我认为你的条件得分很好......但你实际上并没有影响球的运动。
当球移动up
时,它将具有负增量,并且当移动left
时也将具有负增量。
当检测到碰撞时,您需要反转三角形的符号......如:
xChange *= -1;
和yChange *= -1;