[英]Rotating Around a Point
我有一個船的紋理,就在船的機翼下方是導彈紋理。 當我旋轉船時,我需要導彈保持在相對於船的相同位置(即在港口機翼下)。 我讀了一些文章並想出了這個(對不起,它有點亂):
private void RotateWeapons()
{
float x, y;
/*
x = leftMissile.X + (radius * (float)Math.Cos(Rotation));
y = leftMissile.Y + (radius * (float)Math.Sin(Rotation));
*/
leftMissile = Vector2.Transform(leftMissile - center, Quaternion.CreateFromAxisAngle(Vector3.Backward, Rotation)) + center;
//leftMissile.X = x;
//leftMissile.Y = y;
}
其中leftMissile
是描述導彈中間的Vector2
,而center
是作為Vector2
的船的中心。 它幾乎可以工作,精靈圍繞中心旋轉。 問題是,它並沒有停留在港口機翼的同一點上。
這很正常:
這是90度,它離機翼更遠:
當旋轉180度時,它甚至不再在船上了:
你應該考慮做的是保持導彈的恆定( readonly
) 偏離你的船:
//non-rotated, where is the missile relative to the ship?
readonly Vector2 missileOffset = new Vector2(5.0f, 2.0f);
這使事物保持在船的相對空間中。 然后,您只需轉換偏移量,然后將其添加到船舶的位置:
//rotation of ship as quaternion
Quaternion rotation = Quaternion.CreateFromAxisAngle(Vector3.Backward, angle);
//the final position for the missile
Vector2 leftMissile = Vector2.Transform(missileOffset, rotation) + shipPosition;
這將使導彈處於適當的位置。 然后,假設您正在使用SpriteBatch
,只需通過將角度傳遞給兩者來旋轉船只和導彈:
batch.Begin();
batch.Draw(shipTex, shipPosition, null, Color.White, angle, Vector2.Zero, 1.0f, SpriteEffects.None, 1.0f);
batch.Draw(missileTex, leftMissile, null, Color.White, angle, Vector2.Zero, 1.0f, SpriteEffects.None, 1.0f);
batch.End();
如果你有一個前向矢量和中心,很容易計算它。
向前規范化。
Forward.Normalize();
獲取正常向量以進行轉發。
Normal.X = Forward.Y; Normal.Y = -Forward.X;
得到導彈的位置。
MissilePos = CenterShip - 前進*偏移(+或 - )正常*偏移X;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.