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

时间:2016-01-04 03:37:41

标签: 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' s'' e'或&# 39; W&#39 ;.我尝试了一系列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。我怎么做才能返回正确的墙,无论它与边缘接触的角度如何?

1 个答案:

答案 0 :(得分:0)

我怀疑问题是你只在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(); } } ,而不在外面,这段代码可以运行:

{!! Form::open(['action' => 'HangoutController@index']) !!}

    <div class="form-group">
        {!! Form::label('title', 'Title:') !!}
        {!! Form::text('title', null, ['class' => 'form-control']) !!}
    </div>

    <div class="form-group">
        {!! Form::label('subtitle', 'Description:') !!}
        {!! Form::textarea('subtitle', null, ['class' => 'form-control']) !!}
    </div>

    <div class="form-group">
        {!! Form::submit('Create Hangout',['class' => 'btn btn-primary form-control']) !!}
    </div>

{!! Form::close() !!}