/****
* Classes
****/
// Bullet class
var Bullet = Container.expand(function () {
var self = Container.call(this);
var bulletGraphics = self.attachAsset('bullet', {
anchorX: 0.5,
anchorY: 0.5
});
self.speed = -10;
self.update = function () {
self.y += self.speed;
// Check if the bullet is off-screen and needs to be removed
if (self.y < -self.height) {
self.destroy();
}
};
});
// Assets will be automatically created and loaded by the LK engine based on usage in the game code.
// Hero class
var Hero = Container.expand(function () {
var self = Container.call(this);
var heroGraphics = self.attachAsset('hero', {
anchorX: 0.5,
anchorY: 0.5
});
self.update = function () {
// Hero update logic, such as movement, can be added here.
};
});
// 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;
// Check if the obstacle is off-screen and needs to be removed
if (self.y > 2732 + self.height) {
self.destroy();
}
};
});
/****
* Initialize Game
****/
var game = new LK.Game({
backgroundColor: 0x000000 // Initialize game with a black background
});
/****
* Game Code
****/
var hero;
var obstacles = [];
var bullets = [];
var score = 0;
var scoreTxt;
function spawnObstacle() {
var obstacle = new Obstacle();
obstacle.x = Math.random() * (2048 - obstacle.width) + obstacle.width / 2;
obstacle.y = -obstacle.height / 2;
obstacles.push(obstacle);
game.addChild(obstacle);
}
function fireBullet() {
var bullet = new Bullet();
bullet.x = hero.x;
bullet.y = hero.y - hero.height / 2 - bullet.height / 2;
bullets.push(bullet);
game.addChild(bullet);
}
function checkCollisions() {
bullets.forEach(function (bullet, bulletIndex) {
obstacles.forEach(function (obstacle, obstacleIndex) {
if (bullet.intersects(obstacle)) {
bullet.destroy();
obstacle.destroy();
bullets.splice(bulletIndex, 1);
obstacles.splice(obstacleIndex, 1);
score += 10;
scoreTxt.setText("Score: " + score);
}
});
});
}
// Initialize hero
hero = new Hero();
hero.x = 1024; // Center horizontally
hero.y = 2732 - 200; // Position from the bottom
game.addChild(hero);
// Initialize score display
scoreTxt = new Text2("Score: 0", {
size: 100,
fill: "#ffffff"
});
LK.gui.top.addChild(scoreTxt);
// Game update function
game.update = function () {
if (LK.ticks % 120 == 0) {
// Spawn an obstacle every 2 seconds
spawnObstacle();
}
if (LK.ticks % 30 == 0) {
// Fire a bullet every 0.5 seconds
fireBullet();
}
checkCollisions();
};
// Touch event to move the hero
game.down = function (x, y, obj) {
var gamePos = game.toLocal(obj.global);
hero.x = gamePos.x;
};
game.move = function (x, y, obj) {
var gamePos = game.toLocal(obj.global);
hero.x = gamePos.x;
};