2012-04-13 100 views
0

我想將對象移動到給定的角度,但它只能向上和向下移動,只能移動Y軸。
Vector2 unitV = new Vector2((float)Math.Sin(player.angle), (float)Math.Cos(player.angle));
unitV.Normalize();
player.model.Position += Vector2.Multiply(unitV,player.model.Speed) * (float)gameTime.ElapsedGameTime.TotalSeconds;
C#Vector2如何向一個角度移動一個對象

+1

您的代碼看起來不錯,我(但我很累!)。在設置'player.model.Position'之前,Vector2.Multiply(unitV,player.model.Speed)*(float)gameTime.ElapsedGameTime.TotalSeconds'的實際值是多少? – spender 2012-04-13 20:45:26

+0

http://www.riemers.net/eng/Tutorials/XNA/Csharp/series2d.php – phadaphunk 2012-04-13 22:47:38

+0

謝謝你,我以其他方式做到了 – 2012-04-23 15:42:21

回答

1

我在練習時遇到了這個問題,但這裏是我找到的解決方案。我希望這會對你有用。使用XNA 4 C sharp。

聲明:

Texture2D sprite; 
Vector2 spritePosition = Vector2.Zero; 
Vector2 spriteOriginalPos; 
float spriterotation = 0; 
float anglecorrection = (Math.PI * 90/180.0); 
float speed = 1; 

注意,anglecorrection被移動的對象向它的「向上」的角度需要。

負載:

//Load basic texture to make it recognizable :) 
sprite= Content.Load<Texture2D>("spritetexture"); 
//Default position in middle 
spritePosition = new Vector2(
        (graphics.GraphicsDevice.Viewport.Width/2) - (sprite.Width/2), 
        (graphics.GraphicsDevice.Viewport.Height/2) - (sprite.Height/2)); 
//Sprite centering 
spriteOriginalPos.X = sprite.Width/2; 
spriteOriginalPos.Y = sprite.Height/2; 

更新:

if (Keyboard.GetState(PlayerIndex.One).IsKeyDown(Keys.Up)) 
{ 
    spritePosition.X += speed * (float)Math.Cos(spriterotation - anglecorrection); 
    spritePosition.Y += speed * (float)Math.Sin(spriterotation - anglecorrection); 
} 

抽獎:

spriteBatch.Draw(sprite, spritePosition, null, Color.Black, spriterotation, spriteOriginalPos, 1.0f, SpriteEffects.None, 0f); 
相關問題