【发布时间】:2019-08-14 10:55:44
【问题描述】:
在移动相机时,我无法在控件上获得正确的鼠标位置。控制器的宽度为 800 像素,高度为 600 像素。
让我们只看绘图方法:在这里,我唯一想做的事情 就是从屏幕中心到鼠标位置画一条线。问题是当相机移动时,结果与相机在位置x: 0, y: 0时的结果不一样。
protected override void Draw()
{
GraphicsDevice.Clear(new Color(50, 50, 50));
SpriteBatch.Begin(SpriteSortMode.Deferred,BlendState.AlphaBlend, null, null, null, null,
Camera.GetTransformationMatrix());
Map.Draw(SpriteBatch);
//SelectionTool.Draw(SpriteBatch);
if (isPanning)
{
var point = PointToClient(MousePosition);
Vector2 mousePosition = new Vector2(point.X, point.Y);
Console.WriteLine(mousePosition);
DrawLine(SpriteBatch, Camera.CenterScreen, mousePosition, Color.White);
}
SpriteBatch.End();
}
所以,我使用Camera.GetTransformationMatrix()来绘制控件:
public Matrix GetTransformationMatrix()
{
return Matrix.CreateScale(new Vector3(1, 1, 0)) *
Matrix.CreateTranslation(new Vector3(-View.X, -View.Y, 0));
}
为了移动我申请的相机:
public void Move(Vector2 distance)
{
View.X += (int)(distance.X * panSpeed);
View.Y += (int)(distance.Y * panSpeed);
}
画线法:
public void DrawLine(SpriteBatch spriteBatch, Vector2 from, Vector2 to, Color color, int width = 1)
{
Rectangle rect = new Rectangle((int)from.X, (int)from.Y, (int)(to - from).Length() + width, width);
Vector2 vector = Vector2.Normalize(from - to);
float angle = (float)Math.Acos(Vector2.Dot(vector, -Vector2.UnitX));
Vector2 origin = Vector2.Zero;
if (from.Y > to.Y)
angle = MathHelper.TwoPi - angle;
SpriteBatch.Draw(lineTexture, rect, null, color, angle, origin, SpriteEffects.None, 0);
}
结果:
Camera hasn't moved
Camera has moved to the right
我尝试反转矩阵以及使用PointToClient 或PointToScreen,但没有成功。
【问题讨论】:
标签: c# forms winforms monogame mouse-position