Drawing a Projectile’s Trajectory Path

The previous post went through how to simulate the flight of an arrow. However, since the flight is parabolic it may be difficult for the player to be accurate when firing the weapon. Maybe that’s the way you want it, but you can always provide some guidance while still keeping the game challenging.

Let’s build on the arrow example and add a partial trajectory path of the arrow that helps the player accurately hit targets at a distance. Try the example below.

This is what was added to arrow example to show the trajectory path:

  • A clause was added to the global update function to draw the trajectory path based on the current position of the mouse on the canvas.
  • Added functions to calculate and draw the trajectory path on the canvas based on the position of the mouse on the canvas.

Below is the main function that draws the trajectory path. The input values are the starting position of the arrow, the angle of fire, and the force applied to the arrow. In the example, the position is fixed, but in the game it would be the coordinate of the entity firing the arrow. The angle is calculated based on the position of the mouse and the starting position. The force is also constant, but could be variable based on user input, e.g. how long the mouse button is pressed.

The example uses ray casting to determine where the arrow would collide with a body. You could add your own logic here to ignore certain bodies or display different colored trajectory markers depending on what is hit.

The example draws up a lot of trajectory markers. This is mainly for illustrative purposes and is controlled by the value in the variable numTrajectoryPoints. Decrease the number to show fewer trajectory markers.

Download the source code:  trajectory.js (689 downloads)