Skip to content

Instantly share code, notes, and snippets.

@1RedOne
Created November 9, 2023 15:37
Show Gist options
  • Save 1RedOne/fc0bb07903cfdf7b220a90ca930e2dac to your computer and use it in GitHub Desktop.
Save 1RedOne/fc0bb07903cfdf7b220a90ca930e2dac to your computer and use it in GitHub Desktop.
Basic Ball Bouncing on Grid example in phaser 3
function preload() {
this.load.image('ball', 'bullet.png');
this.load.image('tile', 'turret.jpeg');
}
function addBall(physics, tilesGroup, x, y, color) {
var ball1 = physics.add.sprite(x, y, 'ball');
ball1
.setScale(0.1)
.setBounce(1)
.setVelocity(400, 200)
.setTint(color)
.setCollideWorldBounds(true);
ball1.targetColor = color;
ball1.onCollide = true;
physics.add.overlap(ball1, tilesGroup, changeTileColor);
}
function create() {
const tileSize = 75; // Set the size of each tile
const rows = 8; // Number of rows
const cols = 10; // Number of columns
// Create a group to hold the tiles
const tilesGroup = this.add.group();
for (let i = 0; i < rows; i++) {
for (let j = 0; j < cols; j++) {
const x = j * tileSize;
const y = i * tileSize;
const tile = this.physics.add.sprite(x, y, 'tile');
tile.setScale(0.1);
tile.onCollide = true;
tile.color = 'white';
tile.setImmovable(true); // Make the tiles immovable
tile.setTint(0xFFFFFF)
tilesGroup.add(tile);
}
}
this.physics.world.setBounds(0, 0, 800, 600); // Set world bounds
addBall(this.physics, tilesGroup, 50, 50, 0xFF2277);
addBall(this.physics, tilesGroup, 400, 249, 0x99FF99);
}
function changeTileColor(ball, tile) {
if (tile.color !== ball.targetColor) {
tile.color = ball.targetColor;
tile.setTint(ball.targetColor);
tile.setAlpha(1);
var rand = Math.floor(Math.random() * 70);
ball.setVelocityX(-ball.body.velocity.x + rand); // Reverse the ball's X velocity
ball.setVelocityY(-ball.body.velocity.y - rand); // Reverse the ball's Y velocity
ball.rotation += 0.1;
}
return true;
}
var config = {
type: Phaser.AUTO,
width: 800,
height: 600,
scene: {
preload: preload,
create: create,
},
physics: {
default: 'arcade',
arcade: {
gravity: { y: 0 }, // No gravity in this example
},
},
};
var game = new Phaser.Game(config);
console.log("game loaded");
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>My Phaser Game</title>
<!-- Load Phaser 3 from a CDN -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/phaser/3.60.0/phaser.min.js"></script>
<!-- Load your game code from a local file -->
<script src="newTile.js"></script>
</head>
<body>
<!-- The game will be created inside this div -->
<div id="game"></div>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment