2016-05-15 139 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 

     }