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?
1 Answer
\$\begingroup\$
\$\endgroup\$
2
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
-
-
\$\begingroup\$ @Bryan Please note a correction I have made to my answer - I just noticed I had
sin
andcos
reversed! (Angles should bex = cos
andy = sin
.) \$\endgroup\$ Commented Jun 9, 2013 at 9:17