/****
* Classes
****/
//<Assets used in the game will automatically appear here>
// Car class
var Car = Container.expand(function () {
var self = Container.call(this);
var carGraphics = self.attachAsset('car', {
anchorX: 0.5,
anchorY: 0.5
});
self.speed = 0;
self.update = function () {
self.y += self.speed;
};
});
// Obstacle class
var Obstacle = Container.expand(function () {
var self = Container.call(this);
var obstacleGraphics = self.attachAsset('obstacle', {
anchorX: 0.5,
anchorY: 0.5
});
self.speed = 5;
self.update = function () {
self.y += self.speed;
};
});
/****
* Initialize Game
****/
var game = new LK.Game({
backgroundColor: 0x000000 //Init game with black background
});
/****
* Game Code
****/
// Initialize arrays and variables
var car;
var obstacles = [];
var scoreTxt;
var gameOver = false;
// Initialize the car
function initCar() {
car = new Car();
car.x = 2048 / 2;
car.y = 2732 - 200;
game.addChild(car);
}
// Initialize the score text
function initScore() {
scoreTxt = new Text2('0', {
size: 150,
fill: "#ffffff"
});
scoreTxt.anchor.set(0.5, 0);
LK.gui.top.addChild(scoreTxt);
}
// Handle move events
function handleMove(x, y, obj) {
if (!gameOver) {
car.x = x;
}
}
// Handle game over
function handleGameOver() {
gameOver = true;
LK.effects.flashScreen(0xff0000, 1000);
LK.showGameOver();
}
// Update game state
game.update = function () {
if (gameOver) return;
// Update car
car.update();
// Update obstacles
for (var i = obstacles.length - 1; i >= 0; i--) {
obstacles[i].update();
if (obstacles[i].y > 2732) {
obstacles[i].destroy();
obstacles.splice(i, 1);
}
if (car.intersects(obstacles[i])) {
handleGameOver();
}
}
// Spawn new obstacles
if (LK.ticks % 60 == 0) {
var newObstacle = new Obstacle();
newObstacle.x = Math.random() * 2048;
newObstacle.y = -50;
obstacles.push(newObstacle);
game.addChild(newObstacle);
}
// Update score
scoreTxt.setText(LK.getScore());
};
// Initialize game elements
initCar();
initScore();
// Set event listeners
game.move = handleMove;
game.down = handleMove;
game.up = function (x, y, obj) {
// No action needed on up event
};