in libgdx game
I want to touchDown and then drag somewhere and then on the release (touchUp) apply a directional force based on the distance and direction from the target body. When you touchdown the target body stays still and then on touchup the force is applied along the desired trajectory.
(very similar to Angry birds - where you get to see the trajectory in dotted lines for the target body when you hold hack the slingshot - I want to do the same)
So I guess that this might not be the hardest thing to do but given a few options Im leaning towards using a MouseJointDef but its an immediate force applied (i.e. the target moves immediately - I want it to stay still and then once the touchup event happens then apply the force)
Whats the easiest way to draw the trajectory also? Im using Box2D also.
Create a class that inherits InputAdapter
class, then create an instance of it and register it to listen the touch inputs.
Gdx.input.setInputProcessor(inputAdapter);
There are 3 methods to handle the touch events touch_down
, touch_dragged
and touch_up
that you have to override.
In touch_down
, check the touching position to whether is in the birds area or not. If it is, make a boolean flag true.
In touch_dragged
, check the flag above and if it was true, calculate the distance of the touch position relative to the bird shooting center and the shooting angle.
In touch_up
, you can order to shoot with the calculated amounts by calling
body2shoot.applyLinearImpulse(impulse, body2shoot.getWorldCenter());
There is no need to MouseJointDef
to move the body2shoot
. Just set the transform of body2shoot
in touching position to be dragged in each cycle of render.
For calculating the trajectory I wrote a class like this:
public class ProjectileEquation
{
public float gravity;
public Vector2 startVelocity = new Vector2();
public Vector2 startPoint = new Vector2();
public ProjectileEquation()
{ }
public float getX(float t)
{
return startVelocity.x*t + startPoint.x;
}
public float getY(float t)
{
return 0.5f*gravity*t*t + startVelocity.y*t + startPoint.y;
}
}
and for drawing it just I set the startPoint
and startVelocity
and then in a loop I give a t
(time) incrementally and call getX(t)
and getY(t)
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With