0
我正在C#WFA中製作一個移動的矩形。它移動沒有問題,但它可以離開我的GUI,所以我需要檢查我的矩形是否出界。我試過了,但它只能在左上角運行。感謝您的幫助(我的窗口是400×400)C#檢查對象是否超出範圍(GUI)
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace Object
{
public partial class Form1 : Form
{
enum Directions { Left, Right, Up, Down }
Directions _direct;
private int _x;
private int _y;
public Form1()
{
InitializeComponent();
_x = 50;
_y = 50;
_direct = Directions.Down;
}
private void Form1_Load(object sender, EventArgs e)
{
Invalidate();
}
private void form_paint(object sender, PaintEventArgs e)
{
e.Graphics.FillRectangle(Brushes.Black, _x, _y, 70, 70);
}
private void timer1_Tick(object sender, EventArgs e)
{
if (_direct == Directions.Left)
{
_x -= 10;
checkPosition(_x, _y);
}
else if (_direct == Directions.Right)
{
_x += 10;
checkPosition(_x, _y);
}
else if (_direct == Directions.Down)
{
_y += 10;
checkPosition(_x, _y);
}
else if (_direct == Directions.Up)
{
_y -= 10;
checkPosition(_x, _y);
}
Invalidate();
checkPosition(_x, _y);
}
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Left)
{
_direct = Directions.Left;
}
else if (e.KeyCode == Keys.Right)
{
_direct = Directions.Right;
}
else if (e.KeyCode == Keys.Up)
{
_direct = Directions.Up;
}
else if (e.KeyCode == Keys.Down)
{
_direct = Directions.Down;
}
}
private void checkPosition(int x, int y) {
if (x < 0) {
_x = 0;
}
else if (y < 0) {
_y = 0;
}
else if ((x + 70) > 400) { _x = 330; }
else if ((y+70)>400) {_y=330;}
}
}
}
您應該至少刪除'checkPosition'中的所有'else',在這種情況下,它看起來不是原因,但稍後它可能會咬你。 – hultqvist
感謝您的建議:) – sliziky
不知道確切的問題是什麼,但請注意,如果矩形觸及邊界,您的代碼可能會導致零星的抖動。由於timer1_tick方法可能在UI線程之外的另一個線程上運行,因此在增加/減少_x或_y之後但在調用checkPosition方法以進行邊界檢查之前,UI可能會重新繪製矩形。更好的方法是在邊界檢查後只設置_x和_y *,並用temp變量進行加/減運算(例如,可以使用System.Drawing.Point而不是兩個int變量) – elgonzo