c# - 如何确定鼠标穿过矩形的哪一侧

标签 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 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';
    }

问题是,如果鼠标以一定角度接近东边或西边,它会返回北边或南边。由于点的性质,在 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();
    }
}

关于c# - 如何确定鼠标穿过矩形的哪一侧,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34584364/

相关文章:

html - SVG 对齐到父元素的右下角

c# - 用最小起订量模拟,试图将对象传递给具有多个参数的构造函数

c# - C#'s most effective counterpart to Delphi' s TStringList 是什么?

c# - 有比 'switch on type' 更好的选择吗?

c#:在子项上显示工具提示

c# - 多线程系统.Windows.图形

javascript - Canvas 矩形具有相同的 x 和 y,但不应如此

Android:缩放时确定可视区域的坐标

c# - 如何使用 C# 在 ASP.NET 中将二进制图像显示到 gridview 中?

c# - 如何生成下一个主键值