New book: Physics for JavaScript Games, Animation, and Simulations

By devNo Comments

Today I am very pleased to announce the publication of my new book: Physics for JavaScript Games, Animation, and Simulations. This is essentially a JavaScript ‘translation’ of my previous ActionScript book. The support page for the book is here.

Animation, Books, Game Physics, HTML5, JavaScript, Simulation

Bouncing ball simulation in JavaScript on HTML5 canvas

By devNo Comments

This is a port of the simple bouncing ball simulation to JavaScript on the HTML5 canvas. You can view the result here.

The HTML5 code

<!doctype html>
<html>
 <head>
  <meta charset="utf-8">
  <title>Bouncing ball</title>
  <style>
	body{background-color: #666;}
	#canvas {background-color: #ccc;}
  </style>
 </head>
 <body>
  <canvas id="canvas" width="700" height="500"></canvas>
  <script src= "bouncing_ball.js"></script>
 </body>
</html>

Nothing complicated here, assuming you’re familiar with basic HTML markup. Note the ridiculously simple HTML5 doctype, and the inclusion of a canvas element, on which we’ll draw the animation. We’ve placed the JavaScript code in the file bouncing_ball.js, and it looks like this:

The JavaScript code

// initialise canvas and context
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d'); 

// physical variables
var g = 0.1; // gravity
var fac = 0.8; // velocity reduction factor per bounce
var radius = 20; // ball radius
var color = "#0000ff"; // ball color

// initialise position and velocity of ball
var x = 50;
var y = 50;
var vx = 2;
var vy = 0;

// ensure that code does not run before page has loaded
window.onload = init; 

function init() {
// set up a timer
	setInterval(update, 1000/60); // 60 frames per second
};

function update() {
  // update velocity
  vy += g; // gravity

  // update position
  x += vx;
  y += vy; 

  // handle bouncing
  if (y > canvas.height - radius){
	y = canvas.height - radius;
	vy *= -fac;
  }

  // wrap around
  if (x > canvas.width + radius){
	x = -radius;
  }

  // update the ball
  drawBall();
};

function drawBall() {
	with (context){
		clearRect(0, 0, canvas.width, canvas.height); // clear canvas
		fillStyle = color;
		beginPath();
		arc(x, y, radius, 0, 2*Math.PI, true);
		closePath();
		fill();
	};
};

The code should be self-explanatory, but here is a quick rundown. The first two lines make the canvas element accessible to the JavaScript code by means of the DOM getElementById() method and then specifies the 2D drawing API of canvas using its getContext() method.

var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');

The next 4 lines of code set the values of the acceleration of the ball (due to gravity), the velocity reduction factor each time it bounces, the radius and color of the ball. Next follow 4 more lines that set the initial position and velocity of the ball.

The next 4 lines set up the animation to get the action going.

window.onload = init; 
function init() {
    setInterval(update, 1000/60); 
};

The window.onload function ensures that the init() function is called only when the document has fully loaded. The init() function does just one thing: it calls the setInterval method, which is essentially a timer that repeatedly fires the function specified as the first argument (here it’s update) after an interval specified in milliseconds as the second argument (here it’s 1000/60, or approximately 16.7 milliseconds – 60 being the frame rate per second).

The update() function, which is called 60 times per second, looks like this:

function update() {
  vy += g;
  x += vx;
  y += vy; 
 
  if (y > canvas.height - radius){
    y = canvas.height - radius;
    vy *= -fac;
  }
 
  if (x > canvas.width + radius){
    x = -radius;
  }
  drawBall();
};

The first line increments the vertical velocity by applying the acceleration due to gravity, followed by two lines that update the position of the ball by the current values of the velocity components. Next, the two if blocks of logic handle the bouncing (by reversing the vertical velocity and reducing its magnitude on each bounce) and wraps the ball around when it leaves the canvas so that it reappears from the other side. Finally, the drawBall() method is called. It looks like this:

function drawBall() {
    with (context){
        clearRect(0, 0, canvas.width, canvas.height); 
        fillStyle = color;
        beginPath();
        arc(x, y, radius, 0, 2*Math.PI, true);
        closePath();
        fill();
    };
};

This code uses methods of the 2D drawing API to first clear the canvas, then draw a filled circle using the arc() method. Recall that this is done at each time step – the animation takes place by wiping the canvas clean and redrawing the ball in a slightly different position every time step.

That’s it – not very hard, is it? There are endless ways of enhancing the realism by introducing more and more physics effects such as friction, wind and so on. We’ll look at some of these effects in future posts.

 

Animation, Game Physics, HTML5, JavaScript, Simulation

Simple physics simulation example: a bouncing ball

By dev3 Comments

In this post, I’d like to share with you just how easy it is to produce a realistic bouncing ball simulation using only a few lines of ActionScript code. It’s the first example from my recently published ActionScript physics book.

Although simple, this example is instructive because it employs a few key physics animation coding techniques. I regard it as a minimal yet non-trivial “hello world” example of physics programming.

The Physics

At the simplest level, there are only two pieces of physics to understand and apply:

Gravity and acceleration

The physics that governs the motion of a bouncing ball is quite simple. The ball is pulled downward by gravity, which causes it to accelerate vertically downward. Acceleration means that its velocity changes with time. In turn, its velocity makes the ball change position in time. Because gravity acts downwards it does not affect the horizontal motion of the ball. Hence, the horizontal component of velocity does not change.

Bouncing

Each time the ball hits a surface such as a floor or a wall it experiences a force that pushes it back, making it bounce off the surface. The effect of this force is to reverse the velocity component perpendicular to the wall; for example, a floor reverses the vertical component of velocity. The magnitude of the velocity also decreases as it bounces off, since it loses some energy due to the impact.

The Code

Let’s take a look at some AS3 code that implements this piece of physics:

package {
	import flash.display.Sprite;
	import flash.events.Event;

	public class BouncingBall extends Sprite {
		private var g:Number = 0.1;
		private var vx:Number = 2;
		private var vy:Number = 0;
		private var ball:Ball;

		public function BouncingBall() {
			ball = new Ball();
			ball.x = 50;
			ball.y = 75;
			addChild(ball);
			addEventListener(Event.ENTER_FRAME,onEachTimestep);
		}

		private function onEachTimestep(evt:Event):void{
			vy += g;      

			ball.x += vx;
			ball.y += vy; 

			if (ball.y > 350){
				vy *= -0.8;
			}
		}
	}
}

As you can see, the code is very simple. We begin by setting the values of the acceleration produced by gravity g and the horizontal and vertical velocity components vx and vy. In the constructor we create a Ball instance (in this case we have a movie clip in the Flash library with a class name of Ball) and set its initial position. The real physics is in the onEachTimestep() method, which runs well, on each time step.

The first line of code in onEachTimestep() increments the vertical velocity by an amount equal to the acceleration due to gravity. Note that the horizontal velocity is not incremented, since gravity does not affect it. The next two lines of code then increment the horizontal and vertical position of the ball by an amount equal to the respective velocity components.

Bouncing is handled by the if logic, which reverses and reduces the vertical velocity component each time the ball hits the ground.

That’s all. You can download the source files here.  Here’s a screenshot of what you should see.

Bouncing ball

A simple bouncing ball simulation

 

Other things to consider

It’s amazing how realistic the animation looks with so little physics and code. It’s fairly straightforward to add other environmental effects and forces for added realism, such as air resistance (drag), ground friction, wind and so on. But we’ll leave these for another post.

 

ActionScript, Animation, Game Physics, Simulation

Time warp

By devNo Comments

A time warp is probably the reason why nothing has happened on this blog in the last six months. Meanwhile the book – Physics for Flash Games, Animation, and Simulations – has been released. Apress has done a great job and the book looks nice – makes me want to read it!

books

If you are one of the early readers then I’d love to hear from you.

General

Birth of a new physics blog

By dev3 Comments

I’ve been threatening to blog about physics for quite a while. The imminent release of my book “Physics for Flash Games, Animation, and Simulations” means that now is a very good time to take up blogging seriously. The initial idea is that the blog will prove useful to readers of the book, and provide an opportunity to engage more directly with them. But let’s see where this takes us…

General
Blue Taste Theme created by Jabox