I want to move an object to the given angle, But it moves only up, and down, only Y axis.
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;
Asked
Active
Viewed 2,313 times
0

Abdyresul Charyev
- 58
- 1
- 8
-
1Your code looks fine to me (but I am very tired!). Before you set `player.model.Position`, what is the actual value of `Vector2.Multiply(unitV,player.model.Speed) * (float)gameTime.ElapsedGameTime.TotalSeconds`? – spender Apr 13 '12 at 20:45
-
http://www.riemers.net/eng/Tutorials/XNA/Csharp/series2d.php – phadaphunk Apr 13 '12 at 22:47
-
thank u, i did it in other way – Abdyresul Charyev Apr 23 '12 at 15:42
1 Answers
1
I just met this problem while practicing, but here is the solution i found. I hope this will work for you. Used XNA 4 C sharp.
Declaration:
Texture2D sprite;
Vector2 spritePosition = Vector2.Zero;
Vector2 spriteOriginalPos;
float spriterotation = 0;
float anglecorrection = (Math.PI * 90 / 180.0);
float speed = 1;
Note that the anglecorrection is needed to move the object toward its "up" angle.
Load:
//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;
Update:
if (Keyboard.GetState(PlayerIndex.One).IsKeyDown(Keys.Up))
{
spritePosition.X += speed * (float)Math.Cos(spriterotation - anglecorrection);
spritePosition.Y += speed * (float)Math.Sin(spriterotation - anglecorrection);
}
Draw:
spriteBatch.Draw(sprite, spritePosition, null, Color.Black, spriterotation, spriteOriginalPos, 1.0f, SpriteEffects.None, 0f);

mousetwentytwo
- 103
- 1
- 2