首页 > 解决方案 > 时间:2019-05-10 标签:c#monogame逐渐旋转玩家身后的相机

问题描述

您好,我正在用 c#monogame 开发游戏,并且在将相机重置回玩家身后时遇到问题。

当玩家按住左键单击时,他能够围绕他的角色旋转摄像机。当他向前移动时,摄像机慢慢地回到他身后。旋转应该决定它应该围绕玩家向左还是向右旋转到玩家身后(最短路径)。目前它有时会绕着玩家绕很远的轨道运行,最糟糕的是,currentY 会卡在 1 和 -1 之间,并且像卡住一样快速地来回移动。

double targetY; //this is the radians Y our camera is going to slowly rotate to
double currentY; //this is our current camera radians Y
float rotateSpeed = 5; //this value lets us slow down how fast we rotate towards targetY

double direction = Math.Cos(targetY) * Math.Sin(currentY) - Math.Cos(currentY) * Math.Sin(targetY);

double distance = Math.Min(currentY - targetY, (MathHelper.Pi * 2) - currentY - targetY);

if (direction > 0) 
{
    //rotating left towards targetY
    currentY -= distance / rotateSpeed;
}
else 
{
    //rotating right towards targetY
    currentY += distance / rotateSpeed;
}

我认为不使用 Math.PI 来确定它应该向左还是向右旋转是一个问题,但我无法解决它。

谢谢你。

更新:

所以我一直忙于解决这个问题,我想我已经知道 targetY 的目标旋转,所以我只是使用下面的代码让 currentY 慢慢旋转到 targetY。

if (currentY < targetY)
{
    //simply add currentY by the distance between currentY and targetY / divide it by how slow you want to rotate.
    currentY += (targetY - currentY) / rotateSpeed;
}
if (currentY > targetY)
{
    //simply minus currentY by the distance between currentY and targetY / divide it by how slow you want to rotate.
    currentY -= Math.Abs(targetY- currentY) / rotateSpeed;
}

这个新代码可以正常工作,唯一的问题是,如果玩家旋转分配,那么我让相机在他旋转之后让相机落后于玩家旋转相机旋转相同的次数,直到它到达玩家旋转。我认为要解决这个问题,我需要将播放器和摄像机的旋转限制在 0 弧度和 6.28319 弧度之间,但是上面的新代码将不起作用,因为它必须处理从 6.28319 到 0 的移动,这会破坏它。

谢谢你。

更新#2

到目前为止,仍在忙于尝试这个新代码现在可以在 360 度和 0 度之间正确旋转。但是现在我需要让它工作 180 度,此时相机将从 170 度旋转到 -190 度(使相机 360 旋转完整 360 度到另一侧)而不是它应该从 170 度旋转到 160 度而也仍然从 360 度旋转到 0 度,这是我到目前为止的代码。

float newRotation = targetY;

if (targetY < MathHelper.ToRadians(180) && currentY > MathHelper.ToRadians(180))
{
    newRotation = targetY + MathHelper.ToRadians(360);
}
if (targetY > MathHelper.ToRadians(180) && currentY < MathHelper.ToRadians(180))
{
    newRotation = targetY - MathHelper.ToRadians(360);
}
if (currentY < newRotation)
{
    currentY += (newRotation - currentY) / rotateSpeed;
}
if (currentY > newRotation)
{
    currentY -= Math.Abs(newRotation - currentY) / rotateSpeed;
}

谢谢你。

标签: .netmathrotationmonogameangle

解决方案


我解决了下面的代码将在 360 度和 0 度之间旋转的问题,它也会在 170 度到 160 度之间旋转,仅发布以防万一它有助于其他人。

float newRotation = targetY;

if (targetY < MathHelper.ToRadians(90) && currentY > MathHelper.ToRadians(270))
{
    newRotation = targetY + MathHelper.ToRadians(360);
}
if (targetY > MathHelper.ToRadians(270) && currentY < MathHelper.ToRadians(90))
{
    newRotation = targetY - MathHelper.ToRadians(360);
}
if (currentY < newRotation)
{
    currentY += (newRotation - currentY) / rotateSpeed;
}
if (currentY > newRotation)
{
    currentY -= Math.Abs(newRotation - currentY) / rotateSpeed;
}

我还通过对相机和玩家使用以下代码来阻止玩家在旋转时不断增加或减少他的度数。

if (currentY >= MathHelper.Pi * 2) currentY = 0.0f;
if (currentY < 0) currentY = MathHelper.Pi * 2;

推荐阅读