Get started with melonjs CDN
Stable version
Copied!
How to start using melonjs CDN
// Create a new HTML element for the game canvas
const gameContainer = document.createElement('div');
document.body.appendChild(gameContainer);
// Set the canvas size
gameContainer.style.width = '800px';
gameContainer.style.height = '600px';
// Create a new game instance
const game = new MEGA.Game({
container: gameContainer,
width: 800,
height: 600,
backgroundColor: 0xEEEEEE,
physics: {
default: 'mjs-engine',
gravity: [0, 10]
}
});
// Create a new player object
class Player extends MEGA.GameObject {
constructor() {
super({
x: 400,
y: 400,
sprite: 'player.png',
size: { width: 32, height: 32 }
});
this.addLabel('score', 0, 10, 10, '#FFFFFF');
}
update() {
const moveSpeed = 5;
if (MEGA.Input.isKeyPressed(MEGA.KEY.LEFT)) {
this.x -= moveSpeed;
}
if (MEGA.Input.isKeyPressed(MEGA.KEY.RIGHT)) {
this.x += moveSpeed;
}
if (MEGA.Input.isKeyPressed(MEGA.KEY.UP)) {
this.y -= moveSpeed;
}
if (MEGA.Input.isKeyPressed(MEGA.KEY.DOWN)) {
this.y += moveSpeed;
}
this.label('score').text = `Score: ${Math.floor(Math.random() * 100)}`;
}
}
// Register the player object
game.objects.register('Player', Player);
// Create a new player instance
const player = game.objects.create('Player');
// Start the game
game.start();
Copied!
Copied!