Moonshine

Bouncing balls example

About

This example shows how you can create a custom API in JavaScript and then expose it to and use it in your Lua environment.

Result

Source

<canvas width="300" height="300"></canvas>
(function () {

	var canvas = document.getElementsByTagName('canvas')[0],
		ctx = canvas.getContext('2d'), 
		circles = [],
		api,
		vm,

		WIDTH = 300,
		HEIGHT = 300;



	/*****************
	 * Circle class
	 ****************/

	function Circle (color, radius) {
		this._color = color;
		this._radius = radius;
		this.x = WIDTH / 2;
		this.y = HEIGHT / 2;
	}


	Circle.prototype.update = function () {
		if (this.onUpdate) this.onUpdate.call();
	};


	Circle.prototype.render = function (ctx) {
		ctx.beginPath();
		ctx.arc(this.x, this.y, this._radius, 0, Math.PI*2, true); 
		ctx.closePath();
		ctx.fillStyle = this._color;
		ctx.fill();
	};



	/*****************
	 * Event loop
	 ****************/

	function eventLoop () {
		ctx.clearRect(0, 0, WIDTH, HEIGHT);

		for (var i = 0, circle; circle = circles[i]; i++) {
			circle.update()
			circle.render(ctx);
		}

		window.requestAnimationFrame(eventLoop);
	}

	window.requestAnimationFrame = window.requestAnimationFrame || function (cb) { setTimeout(cb, 1000/60); };
	window.requestAnimationFrame(eventLoop);



	/*****************
	 * API
	 ****************/

	api = {
		createCircle: function (color, radius) {
			var circle = new Circle(color, radius);
			circles.push(circle);
			return circle;
		}
	}


	vm = new shine.VM(api);
	vm.load('./bounce.lua.json');

})();
local colors = { 'red', 'blue', 'green', 'orange', 'yellow', 'purple' }
local balls = {}


for _, color in pairs(colors) do
	local radius = math.random(5, 25)
	local circle = createCircle(color, radius)

	local velX = math.random(-8, 8)
	local velY = math.random(-8, 8)

	circle.onUpdate = function ()
		circle.x = circle.x + velX
		circle.y = circle.y + velY

		if circle.x < radius or circle.x > 300 - radius then velX = -velX end
		if circle.y < radius or circle.y > 300 - radius then velY = -velY end
	end
end