[英]How to determine which side of a rectangle was crossed by the mouse
我正在使用以下代碼來開發一種游戲,其中鼠標被矩形所包圍:
Rectangle box = new Rectangle(113, 113, 276, 276);
char direction;
private void Form1_MouseMove(object sender, MouseEventArgs e)
{
if (box.Contains(e.Location))
{
temp = new Point(e.Location.X, e.Location.Y + 23);
}
else
{
Cursor.Position = temp;
}
}
我需要確定鼠標試圖越過的任何一側,並將字符方向設置為“ n”,“ s”,“ e”或“ w”。 我嘗試了一系列的if語句:
// West - East
if (e.Location.X < temp.X)
{
direction = 'w';
}
if (e.Location.X > temp.X)
{
direction = 'e';
}
// North - South
if (e.Location.Y + 23 < temp.Y)
{
direction = 'n';
}
if (e.Location.Y + 23 > temp.Y)
{
direction = 's';
}
問題在於,如果鼠標以一定角度靠近東側或西側,它將向北或向南返回。 由於點的性質,在WE軸上返回true的語句可以在NS軸上同時返回true。 我怎樣才能使它返回正確的牆,而不管它與邊緣接觸的角度如何?
我懷疑問題在於,您只能在框內而不是外面設置temp
時,此代碼才有效:
Rectangle box = new Rectangle(113, 113, 276, 276);
char direction;
Point temp;
private void Form1_Paint(object sender, PaintEventArgs e)
{
using (Graphics g = this.CreateGraphics())
{
Pen pen = new Pen(Color.Black, 2);
g.DrawRectangle(pen, box);
pen.Dispose();
}
}
private void Form1_MouseMove(object sender, MouseEventArgs e)
{
temp = new Point(e.Location.X, e.Location.Y);
if (box.Contains(temp.X, temp.Y))
{
textBox1.Text = temp.X + " , " + temp.Y;
}
else
{
//COMMENT OUT THIS LINE FOR MOVEMENTS OUTSIDE THE Box
if (textBox1.Text.Length == 1) return;
if (box.Left >= temp.X)
{
direction = 'w';
}
else if (box.Left + box.Width <= temp.X)
{
direction = 'e';
}
else if (box.Top >= temp.Y)
{
direction = 'n';
}
else if (box.Top + box.Height <= temp.Y)
{
direction = 's';
}
textBox1.Text = direction.ToString();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.