2016-05-15 136 views
0

我正在创建一个简单的弹跳球应用程序,它使用计时器来弹出图片框两侧的球,我遇到的麻烦是它从底部反弹,图片框的右侧,但不反弹的顶部或左边,我不知道为什么,球大小为30,如果你想知道检测图片框边缘C#

它的代码是:

using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Data; 
using System.Drawing; 
using System.Text; 
using System.Windows.Forms; 
using System.Drawing.Drawing2D; 

namespace Ball 
{ 
    public partial class Form1 : Form 
    { 
     int x = 200, y = 50;  // start position of ball 
     int xmove = 10, ymove = 10; // amount of movement for each tick 

     public Form1() 
     { 
      InitializeComponent(); 
     } 


     private void Form1_Load(object sender, EventArgs e) 
     { 
     } 

     private void pbxDisplay_Paint(object sender, PaintEventArgs e) 
     { 
      Graphics g = e.Graphics;  // get a graphics object 

       // draw a red ball, size 30, at x, y position 
      g.FillEllipse(Brushes.Red, x, y, 30, 30); 
     } 

     private void timer1_Tick(object sender, EventArgs e) 
     { 
      x += xmove;    // add 10 to x and y positions 
      y += ymove;  
      if(y + 30 >= pbxDisplay.Height) 
      { 
       ymove = -ymove; 
      } 
      if (x + 30 >= pbxDisplay.Width) 
      { 
       xmove = -xmove; 
      } 
      if (x - 30 >= pbxDisplay.Width) 
      { 
       xmove = -xmove; 
      } 
      if (y - 30 >= pbxDisplay.Height) 
      { 
       ymove = -ymove; 
      } 
      Refresh();    // refresh the`screen .. calling Paint() again 

     } 

     private void btnQuit_Click(object sender, EventArgs e) 
     { 
      Application.Exit(); 
     } 


     private void btnStart_Click(object sender, EventArgs e) 
     { 
      timer1.Enabled = true; 
     } 

     private void btnStop_Click(object sender, EventArgs e) 
     { 
      timer1.Enabled= false; 
     } 

    } 
} 

如果有人能看到我的问题是什么,那么请让我知道,非常感谢!

回答

1

那么你的边缘识别方法是错误的。左上角的坐标点坐标为[0,0]。所以你应该检查左和顶零。不是宽度和高度。

所以,你的代码应该是这样的:

private void timer1_Tick(object sender, EventArgs e) 
     { 
      x += xmove;    // add 10 to x and y positions 
      y += ymove;  
      if(y + 30 >= pbxDisplay.Height) 
      { 
       ymove = -ymove; 
      } 
      if (x + 30 >= pbxDisplay.Width) 
      { 
       xmove = -xmove; 
      } 
      if (x - 30 <= 0) 
      { 
       xmove = -xmove; 
      } 
      if (y - 30 <= 0) 
      { 
       ymove = -ymove; 
      } 
      Refresh();    // refresh the`screen .. calling Paint() again 

     }