我有以下Camera类:
public Vector2 Position { get; set; } = Vector2.Zero;
public float Rotation { get; set; } = 0.0f;
public float Zoom
{
get
{
// Negative zoom will flip the image
if (_zoom < 0.1f)
{
_zoom = 0.1f;
}
return _zoom;
}
set
{
_zoom = value;
// Negative zoom will flip the image
if (_zoom < 0.1f)
{
_zoom = 0.1f;
}
}
}
public Matrix Transform(Viewport viewport)
{
int viewportWidth = viewport.Width;
int viewportHeight = viewport.Height;
return
Matrix.CreateTranslation(new Vector3(-Position.X - viewportWidth / 2, -Position.Y - viewportHeight / 2, 0)) * // Translation Matrix
Matrix.CreateRotationZ(Rotation) * // Rotation Matrix
Matrix.CreateScale(new Vector3(Zoom, Zoom, 1)) * // Scale Matrix
Matrix.CreateTranslation(new Vector3(viewportWidth / 2, viewportHeight / 2, 0)); // Origin/Offset Matrix
}
public void Move(Vector2 amount)
{
Position += amount;
}
还有一个Update()
方法,用于检查用户从键盘和鼠标输入的特定内容,例如移动,旋转,缩放。
从我的“变换矩阵”可以看出,当我放大/缩小(递增或递减_zoom
)时,我是朝固定的原点(屏幕的中心)进行缩放。
当它朝着鼠标光标缩放时,如何使它如此?
我阅读了一些类似问题的答案,但无法在相机上实现。任何帮助表示赞赏。
答案 0 :(得分:0)
在“缩放”之前应用另一个“平移”以将缩放集中在鼠标点上。
public Matrix Transform(Viewport viewport)
{
int viewportWidth = viewport.Width;
int viewportHeight = viewport.Height;
return
Matrix.CreateTranslation(new Vector3(-Position.X - viewportWidth / 2, -Position.Y - viewportHeight / 2, 0)) * // Translation Matrix
Matrix.CreateRotationZ(Rotation) * // Rotation Matrix
Matrix.CreateTranslation(new Vector3(-mouseState.X - viewportWidth / 2, -mouseState.Y - viewportHeight / 2, 0)) * //Mouse Translation Matrix
Matrix.CreateScale(new Vector3(Zoom, Zoom, 1)) * // Scale Matrix
Matrix.CreateTranslation(new Vector3(viewportWidth / 2, viewportHeight / 2, 0)); // Origin/Offset Matrix
}