Hi I've just started coding Java and HTML, etc, so I tend to struggle at times. Hence I have joined StackOverflow for your help (Be nice to me please :) )
I'm trying to animate using setInterval()
and draw method to create a bouncing ball which moves by a number of pixels in each frame. When it hits an edge it should bounce back by reversing the direction of the relevant horizontal or vertical pixel velocity.
Here is what has been done so far, my HTML code:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Canvas Example</title>
<script type="text/javascript" src='myanim.js' defer></script>
<style type=text/css>
#mycanvas {border:1px solid #000000}
</style>
</head>
<body>
<canvas id=mycanvas width=600 height=400>Canvas Not Supported
</canvas>
</body>
</html>
My JavaScript:
var canvas=document.getElementById('mycanvas');
var ctx=canvas.getContext('2d');
var timer;
var fillColour = '#FF0000';
var strokeColour = '#FFFFFF';
var x=0; var y=0;
function frameRate(fps) {
timer = window.setInterval(updateCanvas,1000/fps);
}
function noLoop() {
window.clearInterval(timer);
}
function updateCanvas(){
if (Math.random()>0.5)x+=2; else x-=2;
if (Math.random()>0.5)y+=2; else y-=2;
ctx.fillRect(0,0,canvas.width,canvas.height);
draw();
}
function draw(){
ctx.beginPath();
ctx.arc(canvas.width/2+x,canvas.height/2+y,100,0,2*Math.PI);
ctx.stroke();
}
ctx.strokeStyle=strokeColour;
ctx.fillStyle=fillColour;
frameRate(50);
http://jsfiddle.net/6EFqk/265/
I've been helped out by the math.random
as I don't understand it. Can someone help me out on how to do this?
Thanks in advance.
Animating a bouncing ball
Below is an example of a simple bouncing ball. This answer is partly from another answer, but your question title is better suited to being found.
The Main Loop.
To animate you need to have a main loop. This is the function that is called once every time you need to update and draw everything you need onto the canvas. This update is normally called a frame. Then number of times the main loop is called a second is called the frame rate. The typical frame rate of HTML is 60 frames per second or lower. HTML5 provides a special event call requestAnimationFrame that is designed for animations and fires at the best time for you to run the main loop.
To start the animation just call the mainloop after you have everything set up
Request animation frame will do its best to maintain an even frame rate. It will also slow down if your mainloop takes to long.
Bouncing a ball
Below is an example of how to simulate a single bouncing ball and to correctly handle simple collisions will surfaces parallel to the canvas sides.
It demonstrates how to change the frame rate by switching between
requestAnimationFrame
andsetTimeout
to call the main loop function.It has an example of drawing an image, and adding motion blur (NOTE motion blur is GPU (graphics processing unit) intensive and will not work well on large numbers of objects.)
Inter frame movement
The correct way to reflect an object from a surface.
You must take into account that the ball is moving between frames and that the collision may have happened at any time during the previous frame. The ball's distance from the wall after the collision is dependent on when during the previous frame it hit the wall. This is important if the ball moves slowly or quickly.
Why it matters
Below is a simulation of a ball bouncing inside the canvas.
To illustrate that the ball is moving between frames it has been motion blurred to show its motion between frames. Please note this is not the perfect solution as the bounce is assumed to occur while the ball is in linear motion while infact it is in freefall and under constant acceleration. But it still conserves energy.
In the correct test the height the ball bounces back to, stays around the same over time. No energy is lost or gained.
Right click to turn off the inter frame adjustment and you will notice that the ball begins to decrease its height each frame. This is because at each collision the ball loses a little energy because it motion during the previous frame is not taken into account when positioning it after the collision test. It will settle down to a constant rate when the collision occurres at precisely the frame time. When that will be is very hard to determine in advance.
Left click to slow the simulation frame rate, left click again to return to normal.
The code below is not really part of the answer, it is there to demonstrate the effect of not correctly adjusting the position during collision test on the overall accuracy of the simulation.