Skip to main content
7 of 13
added detailed code and explainations
ronscript
  • 501
  • 4
  • 25

How to create a projectile motion of a cannonball in top down view?

Objective

  • To move the bullet with projectile motion.

In the below image is an example of a bullet which has a projectile motion. On my observation, the bullet speed and angle is calculated base on distance.

http://pixwerk.net/home/images/gifs/slimeWeapon.gif

Where I'm at? (How do I move the bullet to its destination?)

In the below code, is the method I use to move a bullet to its destination. But the problem is I want to create a cannonball bullet which it has a projectile motion. How do I create these tricks to make a cannon ball projectile motion like the image below.

public Vector2 getVelocity(Vector2 currentPosition, Vector2 targetPosition) { Vector2 targetDirection = targetPosition.cpy().sub(currentPosition); return targetDirection .nor(); } 

What I have done? (Currently I could move the bullet straight to its destination.)

  • Bullet is moving straight (It's not problem).

[EDIT]

Drawing a projected trajectory

To get the trajectory point, base on iforced example. I've already have the libgdx box2d version of this.

b2Vec2 getTrajectoryPoint( b2Vec2& startingPosition, b2Vec2& startingVelocity, float n ) { //velocity and gravity are given per second but we want time step values here float t = 1 / 60.0f; // seconds per time step (at 60fps) b2Vec2 stepVelocity = t * startingVelocity; // m/s b2Vec2 stepGravity = t * t * m_world->GetGravity(); // m/s/s return startingPosition + n * stepVelocity + 0.5f * (n*n+n) * stepGravity; } 

Rendering the trajectory point

glColor3f(1,1,0); glBegin(GL_LINES); for (int i = 0; i < 180; i++) { // three seconds at 60fps b2Vec2 trajectoryPosition = getTrajectoryPoint( startingPosition, startingVelocity, i ); glVertex2f(trajectoryPosition.x, trajectoryPosition.y ); } glEnd(); 

Problem

This is the problem, I don't know how do I set the starting velocity. Currently in the below code, to set the startingVelocity and startingPosition where the underlined code is the part that I'm not sure.

 touchPoint.set(Gdx.input.getX(), Gdx.input.getY(), 0); camera.unproject(touchPoint); Vector2 touch = new Vector2(touchPoint.x, touchPoint.y); Vector2 touchDirection = touch.cpy().sub(bulletPosition).nor(); // get the the direction from bullet position to touch point and normalize the value. startingPosition.set(cameraWidth / 2, cameraHeight / 2); // set position to the center of camera float distance = touchDirection.dst(startingPosition); float angle = touch.angle(); // @TODO how do I set this velocity base on mouse move startingVelocity.x = 10; // 10 meters startingVelocity.y = 0; startingVelocity.rotate(angle); 

How do I set the startingVelocity base on mouse move ??

 startingVelocity.x = 10; // 10 meters startingVelocity.y = 0; startingVelocity.rotate(angle); 
ronscript
  • 501
  • 4
  • 25