首页 > 解决方案 > 围绕一个点的 2D 矢量旋转(小地图)

问题描述

我正在尝试做的事情:

  1. 用当前玩家的位置和敌人的位置渲染一个小地图。
  2. 2D 小地图上的“向上”方向应始终显示游戏中玩家前方的内容,然后正确的方向应显示玩家右侧的内容,向下和左侧相同。
  3. 玩家应该始终以小​​地图为中心。

我已经做了什么:

根据游戏中的 x 和 y 坐标在小地图上渲染玩家,根据 x 和 y 坐标在小地图上渲染敌人。当我在游戏中四处移动时,小地图中的敌人会相对于玩家的移动而移动。

我尝试过的(但没有用):

float radarX = 200;
float radarY = 200;
float zoom = 2;

// Function
float xOffset = radarX - LocalPlayer.Position.x;
float yOffset = radarY - LocalPlayer.Position.y;

draw(zoom *(LocalPlayer.Position.x + xOffset),
zoom * (LocalPlayer.Position.y + yOffset);

foreach(Player p in Game.OtherPlayers) // list of enemies
{
Vector2 rotatedLocation = VectorExt.Rotate(new Vector2(p.Position.x, p.Position.y), -LocalPlayer.Yaw - 90); // negate and -90 to convert to normal coordinate system (0 @ RHS, 90 @ Top, 180 @ LHS, 270 @ Bottom)

float tempX = zoom * (rotatedLocation.x + xOffset);
float tempY = zoom * (rotatedLocation.y + yOffset);

draw(myPen, zoom * (LocalPlayer.Position.x + xOffset), zoom * (LocalPlayer.Position.y + yOffset);
}
// End of function

// VectorExt.Rotate
var ca = Math.Cos(radians);
var sa = Math.Sin(radians);
return new Vector2(Convert.ToSingle(ca * v.x - sa * v.y), Convert.ToSingle(sa * v.x + ca * v.y));
// End of VectorExt.Rotate

提前致谢。

标签: c#math

解决方案


当您在游戏中旋转玩家时,敌人会旋转,但它们似乎是围绕 0,0 轴而不是玩家旋转。

是的,这就是您的轮换代码的作用。要绕另一点旋转,您必须先减去该旋转中心的坐标,然后进行旋转,然后再次添加旋转中心的坐标。

另请参阅this other C++ question


推荐阅读