Game Development Stack Exchange is a question and answer site for professional and independent game developers. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

How can I shoot a ball in a certain angle? When I press the Space key, the ball should be shot in a 45 degree angle. How can I do that?

share|improve this question
up vote 3 down vote accepted
float angle = MathHelper.ToRadians(45);
float power = 20; // <- tunable value

Vector2 direction = new Vector2((float)Math.Cos(angle), (float)Math.Sin(angle));

fixture.Body.ApplyLinearImpulse(power * direction);

The above applies an instantaneous force to the object. You could also set Body.LinearVelocity directly.

To check for the space key being pressed (rather than held down), you want to do something like this:

 KeyboardState keyboardState = Keyboard.GetState();

 if(keyboardState.IsKeyDown(Keys.Space) && lastKeyboardState.IsKeyUp(Keys.Space))
     // apply the impulse here

 lastKeyboardState = keyboardState; // store this between frames
share|improve this answer
Thanx. It works. – Bryan Jun 8 '13 at 12:24
@Bryan Please note a correction I have made to my answer - I just noticed I had sin and cos reversed! (Angles should be x = cos and y = sin.) – Andrew Russell Jun 9 '13 at 9:17

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.