Projectile algorithm

This document describes and illustrates a way create a projectile-path for 2D movement of objects. Click anywhere on this page to see a very basic example. » View the page source to see the example code.

By choosing a static value of pixels for one of the dimensions, in my case the Y dimension, the moving object will travel in that dimension with a steady progress (a predefined amount of pixels) while the second dimension's movement progress will be adjusted accordingly.

It's like a heat seeking missile. It needs consistent speed toward (first dimension) the target, but can turn sideways (second dimension) with variable speed. There are many uses for this formula.

Pseudo formula (JavaScript):
PixelsPerStepSecondDimension = SecondDimensionLength / (FirstDimensionLength / PixelsPerStepFirstDimension)

/*
 We define Y as first dimension, making the vertical direction the main and static projectile speed.
 The ternary expressions makes sure the projectile object may travel in either direction.
*/
FirstDimensionLength = (start_y>stop_y?start_y-stop_y:stop_y-start_y);
SecondDimensionLength = (start_x>stop_x?start_x-stop_x:stop_x-start_x);
NumberOfSteps = FirstDimensionLength / PixelsPerStepFirstDimension;
PixelsPerStepSecondDimension = Math.round(SecondDimensionLength / NumberOfSteps);
	
for(loop_a=0; loop_a<=NumberOfSteps; loop_a++) {
 next_y = (next_y<stop_y?next_y+PixelsPerStepFirstDimension:next_y-PixelsPerStepFirstDimension);
 next_x = (next_x<stop_x?next_x+PixelsPerStepSecondDimension:next_x-PixelsPerStepSecondDimension);
 PathArray.push([next_x,next_y]);
}


Written by: Dag Jonny Nedrelid
©2007-2012 http://thronic.com


Feel free to leave a comment.
Name:
URL:
0