HTML5.Projectile – A Simple projectile-motion implementation
Last weeks i’ve been working a lot with Ogre 3D engine and by consequence i couldn’t bring something, even little, here on my blog.
The topic is the classic projectile motion (not considering air drag) re-adapted to HTML5 implementation.
So, in IA it’s the oldest one in the book, we’re going to implement the motion equation for both axis:
Δx = v0xt
First, define known parameters:
var pro = {
x:50,
y:380,
r:15,
v:80,
theta: 45
};
Where:
- x and y stays for initial position in the canvas element
- r is the ball radius
- v stays for initial velocity
- theta stays for the launch angle
Then let’s acquire the canvas element and the context:
var canvas = document.getElementById('surface');
var ctx = canvas.getContext('2d');
At this point we have to calculate some variables we’re gonna use in the motion equation:
var frameCount = 0; var v0x = pro.v * Math.cos(pro.theta * Math.PI/180); var v0y = pro.v * Math.sin(pro.theta * Math.PI/180); var startX = pro.x; var startY = pro.y; var g = 9.8;
Where v0x stays for the initial velocity on the x axis (and the same for v0y).
Now it’s about defining the loop function, the one who will be called at each frame:
setInterval(function()
{
//loop code here
}, 1000 / 77);
The rest it’s about updating position frame after frame, considering the time elapsed as frame count
ctx.save(); ctx.fillStyle = "rgba(0, 0, 0, .3)"; ctx.fillRect(0, 0, canvas.width, canvas.height); ctx.restore(); if(pro.yNote that the .3 opacity parameter in the first rect is used to create a trail-motion effect: try to change this value and see the difference.