2
\$\begingroup\$

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?

\$\endgroup\$

1 Answer 1

3
\$\begingroup\$
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
\$\endgroup\$
2
  • \$\begingroup\$ Thanx. It works. \$\endgroup\$
    – Bryan
    Commented Jun 8, 2013 at 12:24
  • \$\begingroup\$ @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.) \$\endgroup\$ Commented Jun 9, 2013 at 9:17

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .