计算Rectangle中单击的位置

时间:2013-10-18 06:37:16

标签: c# vector xna position monogame

我为2D游戏制作了一个简单的Tile地图编辑器。

到目前为止,一切都在运作,但有一点点难看。

如果我拖动瓷砖,它会从瓷砖的(顶部,左侧)拖动,但我想从点击的位置拖动它。

picture of a tile http://s1.directupload.net/images/131018/74zy492i.png

toDrag.hitbox.X  = ((int)cursorPos.X -(int)clickpos.X) + (int)campos.X;

toDrag.hitbox.Y = ((int)cursorPos.Y -(int)clickpos.Y) + (int)campos.Y;

我该如何计算?

2 个答案:

答案 0 :(得分:1)

像Brainarts建议你必须考虑光标的偏移量。

一些工作代码如下所示:

public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            DoubleBuffered = true;
        }

        Rectangle myBox = new Rectangle(0, 0, 30, 30);
        Point mouseDownPos = Point.Empty;
        bool allowMove = false;

        protected override void OnMouseDown(MouseEventArgs e)
        {
            base.OnMouseDown(e);

            if (!myBox.Contains(e.Location))
                return;

            mouseDownPos = new Point(e.Location.X - myBox.Left, e.Location.Y - myBox.Top);

            allowMove = true;
        }

        protected override void OnMouseUp(MouseEventArgs e)
        {
            base.OnMouseUp(e);

            allowMove = false;
        }

        protected override void OnMouseMove(MouseEventArgs e)
        {
            if (!allowMove)
                return;

            myBox.Location = new Point(e.Location.X - mouseDownPos.X, e.Location.Y - mouseDownPos.Y);

            Invalidate();
        }

        protected override void OnPaint(PaintEventArgs e)
        {
            base.OnPaint(e);

            e.Graphics.FillRectangle(Brushes.Aquamarine, myBox);
        }
    }

答案 1 :(得分:0)

考虑光标与图片框或矩形的偏移,不同之处在于您需要使用它来提供您想要的效果:)