C# 如何确定鼠标与矩形的哪一侧相交
我正在开发一种游戏,其中鼠标被一个矩形包围,使用以下代码:C# 如何确定鼠标与矩形的哪一侧相交,c#,winforms,rect,C#,Winforms,Rect,我正在开发一种游戏,其中鼠标被一个矩形包围,使用以下代码: 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 P
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';
}
//西-东
如果(如位置X<温度X)
{
方向='w';
}
如果(如位置X>温度X)
{
方向='e';
}
//南北
如果(如位置Y+23<温度Y)
{
方向='n';
}
如果(如位置Y+23>温度Y)
{
方向='s';
}
问题是,如果鼠标以一定角度靠近东西两侧,它将返回北方或南方。由于点的性质,在W-E轴上返回true的语句可以同时在N-S轴上返回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();
}
}
矩形框=新矩形(113、113、276、276);
煤焦方向;
点温;
私有void Form1_Paint(对象发送器、PaintEventArgs e)
{
使用(Graphics g=this.CreateGraphics())
{
钢笔=新钢笔(颜色:黑色,2);
g、 绘图矩形(笔、盒);
pen.Dispose();
}
}
私有void Form1\u MouseMove(对象发送方,MouseEventArgs e)
{
温度=新点(e.Location.X,e.Location.Y);
如果(方框包含(温度X、温度Y))
{
textBox1.Text=温度X+“,”+温度Y;
}
其他的
{
//注释这一行,以了解方框外的移动
if(textBox1.Text.Length==1)返回;
如果(box.Left>=温度X)
{
方向='w';
}
否则如果(框左+框宽=温度Y)
{
方向='n';
}
否则,如果(box.Top+box.Height)您的代码正确地确定了被击中的墙,但是,鼠标不再以矩形为边界。很抱歉,出现了一些问题,因此我将让您实现解决方案的第二部分…Cursor.Clip=new rectangle(box.Location,box.Size);
按照DidCursor.Clip=new rectangle(box.Location,box.Size);
为边界问题排序?