/****
* Initialize Game
****/
var game = new LK.Game({
backgroundColor: 0x000000
});
/****
* Game Code
****/
var smallCircle = game.addChild(LK.getAsset('smallCircle', {
anchorX: 0.5,
anchorY: 0.5
}));
smallCircle.x = 2048 / 2;
smallCircle.y = 2732 / 2;
// Create boxes around the small circle
var boxPositions = [{
x: smallCircle.x - 180,
y: smallCircle.y
}, {
x: smallCircle.x + 180,
y: smallCircle.y
}, {
x: smallCircle.x,
y: smallCircle.y - 180
}, {
x: smallCircle.x,
y: smallCircle.y + 180
}];
var boxes = [];
for (var i = 0; i < boxPositions.length; i++) {
var box = game.addChild(LK.getAsset('box', {
anchorX: 0.5,
anchorY: 0.5
}));
box.x = boxPositions[i].x;
box.y = boxPositions[i].y;
// Add a random direction property to each box
box.direction = Math.random() * Math.PI * 2;
boxes.push(box);
}
;
// Create a green square at the bottom of the screen
var greenSquare = game.addChild(LK.getAsset('greenSquare', {
anchorX: 0.5,
anchorY: 0.5
}));
greenSquare.x = 2048 / 2;
greenSquare.y = 2732 - greenSquare.height / 2;
game.update = function () {
// Make the small circle move in a random direction
smallCircle.x += Math.cos(Math.random() * Math.PI * 2) * 5;
smallCircle.y += Math.sin(Math.random() * Math.PI * 2) * 5;
// Function to calculate the direction towards the green square
function calculateDirectionToGreenSquare(circle, greenSquare) {
return Math.atan2(greenSquare.y - circle.y, greenSquare.x - circle.x);
}
game.update = function () {
// Function to calculate the direction towards the nearest box
function calculateDirectionToNearestBox(circle, boxes) {
var nearestBox = null;
var nearestDistance = Infinity;
for (var i = 0; i < boxes.length; i++) {
var dx = boxes[i].x - circle.x;
var dy = boxes[i].y - circle.y;
var distance = Math.sqrt(dx * dx + dy * dy);
if (distance < nearestDistance) {
nearestBox = boxes[i];
nearestDistance = distance;
}
}
return Math.atan2(nearestBox.y - circle.y, nearestBox.x - circle.x);
}
// Make the small circle move towards the nearest box
var direction = calculateDirectionToNearestBox(smallCircle, boxes);
smallCircle.x += Math.cos(direction) * 5;
smallCircle.y += Math.sin(direction) * 5;
// Check for collision with the small circle and boxes
for (var i = 0; i < boxes.length; i++) {
if (smallCircle.intersects(boxes[i])) {
console.log("Collision detected with box " + i + "!");
// When a collision is detected, push the box towards the green square
var boxDirection = calculateDirectionToGreenSquare(boxes[i], greenSquare);
boxes[i].x += Math.cos(boxDirection) * 10;
boxes[i].y += Math.sin(boxDirection) * 10;
}
// Check if the box is outside the game field and if so, move it back
if (boxes[i].x < 0) {
boxes[i].x = 0;
}
if (boxes[i].x > 2048) {
boxes[i].x = 2048;
}
if (boxes[i].y < 0) {
boxes[i].y = 0;
}
if (boxes[i].y > 2732) {
boxes[i].y = 2732;
}
// Check if the box intersects with the green square and if so, remove it
if (boxes[i].intersects(greenSquare)) {
boxes[i].destroy();
boxes.splice(i, 1);
i--;
}
}
};
};