/****
* Classes
****/
// Assets will be automatically generated based on usage in the code.
// Ball class for handling the basketball's behavior
var Ball = Container.expand(function () {
var self = Container.call(this);
var ballGraphics = self.attachAsset('basketball', {
anchorX: 0.5,
anchorY: 0.5
});
self.speedX = 0;
self.speedY = 0;
self.isMoving = false;
self.launch = function (speedX, speedY) {
self.speedX = speedX;
self.speedY = speedY;
self.isMoving = true;
};
self.update = function () {
if (self.isMoving) {
self.x += self.speedX;
self.y += self.speedY;
self.speedY += 0.98; // Gravity effect
}
};
self.reset = function () {
self.x = game.width / 2;
self.y = game.height - 200;
self.speedX = 0;
self.speedY = 0;
self.isMoving = false;
};
});
// Hoop class for handling the basketball hoop's behavior
var Hoop = Container.expand(function () {
var self = Container.call(this);
var hoopGraphics = self.attachAsset('hoop', {
anchorX: 0.5,
anchorY: 0.5
});
self.setPosition = function (x, y) {
self.x = x;
self.y = y;
};
});
/****
* Initialize Game
****/
var game = new LK.Game({
backgroundColor: 0x87CEEB // Sky blue background
});
/****
* Game Code
****/
var ball = game.addChild(new Ball());
ball.reset();
var hoop = game.addChild(new Hoop());
hoop.setPosition(game.width / 2, 150); // Position the hoop at the top center
var score = 0;
var scoreTxt = new Text2(score.toString(), {
size: 150,
fill: "#ffffff"
});
scoreTxt.anchor.set(0.5, 0);
LK.gui.top.addChild(scoreTxt);
var startPosition = null;
game.on('down', function (obj) {
var pos = obj.event.getLocalPosition(game);
startPosition = pos;
});
game.on('up', function (obj) {
if (startPosition) {
var endPosition = obj.event.getLocalPosition(game);
var speedX = (endPosition.x - startPosition.x) * 0.1;
var speedY = (endPosition.y - startPosition.y) * 0.1;
ball.launch(speedX, speedY);
startPosition = null;
}
});
LK.on('tick', function () {
ball.update();
// Check for scoring
if (ball.intersects(hoop)) {
score += 1;
scoreTxt.setText(score.toString());
ball.reset();
}
// Reset ball if it goes off-screen
if (ball.y > game.height + 50 || ball.x < -50 || ball.x > game.width + 50) {
ball.reset();
}
});