1

The ball bounced off halfway on the right. However, I wanted it to bounce off the edge on the right. May I know how do I do it right? The codes that I have are as below.

public partial class StartGame : Form
{
    int x; //The x axis from the upper left corner
    int y; //The y axis from the upper left corner 
    int spdX; //The change of x
    int spdY; //The change of y

    public StartGame()
    {
        InitializeComponent();
    }

    private void StartGame_Load(object sender, EventArgs e)
    {
        //Loads the ball on the screen at bottom of the window
        spdX = 1; //The speed of the ball of y
        spdY = 1; //The speed of the ball of x
        x = this.ClientSize.Width / 5; //The x axis the ball is loaded at
        y = this.ClientSize.Height - 10; //The y axis the ball is loaded at
    }

    private void StartGame_Paint_1(object sender, PaintEventArgs e)
    {
        //This is the inner paint color of the circle that is 10 by 10
        e.Graphics.FillEllipse(Brushes.Blue, x, y, 10, 10);
        //This is the outline paint color of the circle that is 10 by 10
        e.Graphics.DrawEllipse(Pens.Blue, x, y, 10, 10); 
    }

    private void timer1_Tick(object sender, EventArgs e)
    {
        y = y + spdY;
        x = x + spdX;

        if (y < 0)
        {
            spdY = -spdY; //if y is less than 0 then we change direction
        }
        else if (x < -5)
        {
            spdX = -spdX;
        }
        else if (y + 10 > this.ClientSize.Height)
        {
            spdY = -spdY; //if y + 10, the radius of the circle is greater than the form width then we change direction
        }
        else if (x + 10 > this.ClientSize.Height)
        {
            spdX = -spdX;
        }

        this.Invalidate(); 
    }
4

2 回答 2

3

它应该是

else if (x + 10 > this.ClientSize.Width)

复制/粘贴错误?:)

于 2013-05-22T03:17:38.623 回答
1

您错误地检查了“x”运动的高度。

改变:

else if (x + 10 > this.ClientSize.Height)

至:

else if (x + 10 > this.ClientSize.Width)
于 2013-05-22T03:18:02.517 回答