//main.js
const config = {
type: Phaser.AUTO,
width: 400,
height: 400,
physics: {
default: "arcade",
arcade: { gravity: { y: 0 } },
},
scene: {
preload: preload,
create: create,
update: update,
},
};
const game = new Phaser.Game(config);
let player;
let cursors;
let fallingObject;
let score = 0;
let scoreText;
function preload() {
this.load.image("player", "player.png");
this.load.image("object", "apple.png");
}
function create() {
// Add player with dimensions
player = this.physics.add.sprite(200, 350, "player");
player.setDisplaySize(30, 30);
player.setCollideWorldBounds(true);
// Add falling object with dimensions
fallingObject = this.physics.add.sprite(
Phaser.Math.Between(25, 375),
0,
"object"
);
fallingObject.setDisplaySize(20, 20);
fallingObject.setVelocityY(150);
// Add collision detection
this.physics.add.collider(player, fallingObject, catchObject, null, this);
// Add score text
scoreText = this.add.text(16, 16, "Score: 0", {
fontSize: "20px",
fill: "#fff",
});
// Input handling
cursors = this.input.keyboard.createCursorKeys();
}
function update() {
// Player movement
if (cursors.left.isDown) {
player.setVelocityX(-200);
} else if (cursors.right.isDown) {
player.setVelocityX(200);
} else {
player.setVelocityX(0);
}
// Reset falling object if it goes out of bounds
if (fallingObject.y > 400) {
resetFallingObject();
}
}
function catchObject(player, object) {
// Increase score and reset object
score += 10;
scoreText.setText("Score: " + score);
resetFallingObject();
}
function resetFallingObject() {
fallingObject.y = 0;
fallingObject.x = Phaser.Math.Between(25, 375);
}