2013-05-22 97 views
1

球在右边的中途弹回。但是,我希望它在右边反弹。我可以知道我该怎么做对吗?我拥有的代码如下。为什么球没有在右边的边缘弹跳

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(); 
    } 
+3

你*写*代码看起来不错。现在是时候开始开发技能来阅读你的代码,并试图找出为什么它有“错误”的行为,而不是问其他人。 – paddy

回答

1

您错误地检查'x'移动的高度。

变化:

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

要:

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

没问题。通常我会提出更多咖啡...... –

3

应该

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

复制/粘贴错误? :)

+0

不客气。我无法告诉你我做了多少次类似的事情。 ;) – John

+2

可能值得一提的是'x'和'y'测试不应该是同一个if-else结构的一部分。他们应该是独立的。否则,当球反弹到角落并且不能正确反映时(因为只有一个条件发生而不是两个),就有可能得到这种情况。 – paddy

+0

非常感谢! – Guang

相关问题