你好,我正在開發一個c#單機游戲,在將攝像機重置到玩家身后時遇到了問題。
當玩家按住左鍵時,他能夠將攝像機繞著他的角色旋轉。當他向前移動時,攝像機會慢慢地重置到他身后。旋轉應該決定它是應該圍繞玩家向左還是向右旋轉到玩家身后(最短的路徑)。目前,它有時會繞著玩家長距離旋轉,最糟糕的是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; //此值讓我們放慢向目標Y旋轉的速度。
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)
{
//向左旋轉到目標Y。
currentY -= distance / rotateSpeed。
}
else[/span
{
//向右旋轉到目標Y {
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度旋轉到另一邊),相反,它應該從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。
}
謝謝你。
uj5u.com熱心網友回復:
我解決了這個問題,下面的代碼可以在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;
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/331103.html
標籤:
