How to plot trajectory based on inital angle and speed with jQuery and javascript

Posted on: November 3rd, 2012 by admin No Comments

I spent a long time looking for any information on this and anything I did find was too complicated for me to understand so hopefully this is a simple explanation.

Fist we need to create an object to hold all our variables.

1
2
3
4
5
6
7
8
var ball = {
	x: 0,
	y: 0,
	speed: 180,
	angle: 50,
	time: 0,
	gravity: 30
};

Now we need to be able to calculate the the x and y coordinates of our ball at each iteration. The formular I found that works is:

1
2
3
4
// first convert angle to radians
angle = angle * Math.PI/180;
x = speed * Math.cos(angle) * time + x;
y = speed * Math.sin(angle) * time -0.5 * gravity * Math.pow(time, 2);

So putting this together with a loop would look like:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
$(document).ready(function(){
	var ball = {
		x: 0,
		y: 0,
		speed: 180,
		angle: 50,
		time: 0,
		gravity: 30
	};
 
	move_object();
 
	function move_object() {
 
		// work out the new position of the ball
		x = ball.speed * Math.cos(ball.angle * Math.PI/180) * ball.time + ball.x;
		y = ball.speed * Math.sin(ball.angle * Math.PI/180) * ball.time -0.5 * ball.gravity * Math.pow(ball.time,2);
		y = ball.y - y;
 
		// set the position of the ball
		$("#ball").css({'left': x, 'top': y});
 
		// incriment time
		ball.time += 0.05;
 
		setTimeout(function(){move_object()}, 10);
 
	}
 
});

A full working example can be seen here: plot trajectory example.

In the example I have also added collission detection with the walls so that it resets once the ball goes off screen. View the source code to see exactly whats going on.