[英]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.