Sunday, May 31, 2015

xna - How to calculate origin and position of a weapon which should be "in hands"?


I'm currently stuck with my game, which is from the top perspective. I'm currently using these sprites for player: (using the second at the top):


enter image description here


And here's what I use for my gun


enter image description here


My problem is that I am not sure how to calculate origin & position to make sure that gun is always in player's hands. This is my code for drawing player and gun


spriteBatch.Draw(Textures.Load("player"), new Vector2(playerPosition.X, playerPosition.Y), new Rectangle(35, 2, 27,27), Color.White, player.rotation, new Vector2(playerWidth / 2, playerHeight / 2), 1f, SpriteEffects.None, 1f);
spriteBatch.Draw(Textures.Load("Guns/deagle"), new Vector2(playerPosition.X, playerPosition.Y), null, Color.White, player.rotation, new Vector2(playerWidth / 2, playerHeight / 2), 1f, SpriteEffects.None, 1f);

With rotation of 0, I'd need to move my gun to playerPosition.Y + 15 to make sure gun is in guy's hands, but when I do it, it looks fine but as soon as I rotate him, it's even more weird than now.



Here's how it currently looks like, with my specified code above.


https://dl-web.dropbox.com/get/capture-14.mp4?w=40052a2d


All I need is to make sure that gun will be always in guy's hands



Answer



You need to offset the gun's position based on the rotation of the player. Here's the first formula that comes to mind:


x = x + offset*cos(rotation)

y = y + offset*sin(rotation)

So in your specific case use this as the gun's position:



new Vector2( playerPosition.X + 15 * (float) Math.Cos(player.rotation), playerPosition.Y + 15 * (float) Math.Sin(player.rotation) )

No comments:

Post a Comment

Simple past, Present perfect Past perfect

Can you tell me which form of the following sentences is the correct one please? Imagine two friends discussing the gym... I was in a good s...