4 Objects to Collect and Objects to Avoid
Collecting items
In the last session we have learned how to create enemies. Now we will learn how to create items that the player can collect.
We will use the same approach as we did with the enemies: we will create an object for each item and store them in an array.
We will also create a function to check if the player has collected an item.
We will also create a function to check if the player has collected an item.
// Make an item object with position, width and height
var item = {
posX: 100,
posY: 100,
width: 20,
height: 20
}
// Store the item in an array
var allItems = [];
allItems.push(item);
// Loop through the array and check if the player has collected an item
for(var i = 0; i < allItems.length; i++){
if(allItems[i].posX == player.posX && allItems[i].posY == player.posY){
allItems.splice(i, 1);
}
// If there are no items left, the game is over
if(allItems.length == 0){
gameOver();
}
Collecting Items with p5.play Library
Let's create a complete game using the p5.play library where an avatar can collect items. The p5.play library makes collision detection much easier!
// Game variables
let player;
let items = [];
let score = 0;
let gameState = "playing"; // "playing", "won", "lost"
function setup() {
createCanvas(600, 400);
// Create the player sprite
player = createSprite(width/2, height/2, 30, 30);
player.shapeColor = color(0, 255, 0); // Green player
// Create collectible items
for (let i = 0; i < 5; i++) {
let item = createSprite(random(50, width-50), random(50, height-50), 20, 20);
item.shapeColor = color(255, 255, 0); // Yellow items
items.push(item);
}
}
function draw() {
background(220);
if (gameState === "playing") {
// Handle player movement
handlePlayerMovement();
// Check for collisions with items
checkItemCollisions();
// Draw all sprites
drawSprites();
// Display score
fill(0);
textSize(16);
text("Score: " + score, 10, 30);
text("Items left: " + items.length, 10, 50);
// Check win condition
if (items.length === 0) {
gameState = "won";
}
} else if (gameState === "won") {
// Win screen
background(0, 255, 0);
fill(255);
textSize(32);
textAlign(CENTER, CENTER);
text("YOU WIN!", width/2, height/2);
text("Score: " + score, width/2, height/2 + 40);
text("Press SPACE to restart", width/2, height/2 + 80);
}
}
function handlePlayerMovement() {
// Move player with arrow keys
if (keyIsDown(LEFT_ARROW)) {
player.velocity.x = -5;
} else if (keyIsDown(RIGHT_ARROW)) {
player.velocity.x = 5;
} else {
player.velocity.x = 0;
}
if (keyIsDown(UP_ARROW)) {
player.velocity.y = -5;
} else if (keyIsDown(DOWN_ARROW)) {
player.velocity.y = 5;
} else {
player.velocity.y = 0;
}
// Keep player within canvas bounds
player.position.x = constrain(player.position.x, 15, width-15);
player.position.y = constrain(player.position.y, 15, height-15);
}
function checkItemCollisions() {
// Check collision between player and each item
for (let i = items.length - 1; i >= 0; i--) {
if (player.overlap(items[i])) {
// Remove the collected item
items[i].remove();
items.splice(i, 1);
// Increase score
score += 10;
// Optional: Add a sound effect here
console.log("Item collected! Score: " + score);
}
}
}
function keyPressed() {
// Restart game when space is pressed
if (key === ' ' && gameState === "won") {
resetGame();
}
}
function resetGame() {
// Clear existing items
for (let item of items) {
item.remove();
}
items = [];
// Reset player position
player.position.x = width/2;
player.position.y = height/2;
// Create new items
for (let i = 0; i < 5; i++) {
let item = createSprite(random(50, width-50), random(50, height-50), 20, 20);
item.shapeColor = color(255, 255, 0);
items.push(item);
}
// Reset game state
score = 0;
gameState = "playing";
}
How the collision detection works
The p5.play library makes collision detection very simple:
createSprite()- Creates sprite objects that can collideoverlap()- Checks if two sprites are touchingremove()- Removes a sprite from the gamedrawSprites()- Draws all sprites automatically
Game Features
- Player Movement: Use arrow keys to move the green square
- Item Collection: Touch yellow squares to collect them
- Score System: Each item gives 10 points
- Win Condition: Collect all items to win
- Restart: Press SPACE to restart after winning
Advanced Features You Can Add
// Add obstacles that block the player
let obstacles = [];
function createObstacles() {
for (let i = 0; i < 3; i++) {
let obstacle = createSprite(random(100, width-100), random(100, height-100), 40, 40);
obstacle.shapeColor = color(255, 0, 0); // Red obstacles
obstacles.push(obstacle);
}
}
// Add enemies that move around
let enemies = [];
function createEnemies() {
for (let i = 0; i < 2; i++) {
let enemy = createSprite(random(50, width-50), random(50, height-50), 25, 25);
enemy.shapeColor = color(255, 0, 255); // Purple enemies
enemies.push(enemy);
}
}
function moveEnemies() {
for (let enemy of enemies) {
// Simple AI: move towards player
let direction = createVector(player.position.x - enemy.position.x,
player.position.y - enemy.position.y);
direction.normalize();
enemy.velocity.x = direction.x * 2;
enemy.velocity.y = direction.y * 2;
}
}
function checkEnemyCollisions() {
for (let enemy of enemies) {
if (player.overlap(enemy)) {
gameState = "lost";
}
}
}
Assignment
Create Your Own Collection Game
1. Modify the game to have different types of items with different point values
2. Add obstacles that block the player's movement
3. Add enemies that chase the player
4. Add a time limit to make the game more challenging
5. Add sound effects when collecting items
6. Create a power-up system (items that give temporary abilities)
Avoiding objects
Example 1: Avoiding static obstacles
// Basic collision detection with p5.play
let sprite; // Player-controlled sprite
let obstacle; // Single obstacle (unused)
let allObstacles; // Group for all obstacles
let img; // Spaceship image
function preload() {
img = loadImage('spaceship.png'); // Load image before setup
}
function setup() {
createCanvas(400, 400);
allObstacles = new Group(); // Initialize obstacle group
// Create 30 random obstacles
for(let i = 0; i < 30; i++){
let x = random(0,width); // Random position
let y = random(0,height);
let o = createSprite(x,y,6,6); // Small 6x6 obstacle
allObstacles.add(o); // Add to group
}
sprite = createSprite(200,200,20,20); // Create player sprite
img.resize(0,30); // Resize image (maintain aspect ratio)
sprite.addImage(img); // Apply image to sprite
}
function draw() {
background(255);
// Sprite follows mouse
sprite.position.x = mouseX;
sprite.position.y = mouseY;
// Check collision between sprite and any obstacle
sprite.collide(allObstacles, kollision); // Calls kollision() on hit
drawSprites(); // Draw all sprites
}
// Called when collision detected
function kollision(spr,obst){
//obst.remove(); // Could remove hit obstacle
//spr.remove(); // Could remove player
textAlign(CENTER);
textSize(48);
text("DEAD", 200,200); // Display game over
console.log("Hit!"); // Debug message in console
}
Example 2:Avoiding falling obstacles
// Avoid the falling obstacles
let ship; // Player's spaceship sprite
let obstacle; // Single obstacle (unused)
let allObstacles; // Group containing all falling obstacles
let shots; // Group containing all player shots
let img; // Spaceship image
function preload() {
img = loadImage('spaceship.png'); // Load spaceship image before setup
}
function setup() {
createCanvas(400, 400);
allObstacles = new Group(); // Create group for obstacles
shots = new Group(); // Create group for bullets
ship = createSprite(200,200,20,20); // Create ship sprite
img.resize(0,30); // Resize image (0 = keep aspect ratio)
ship.addImage(img); // Attach image to sprite
}
function draw() {
background(255);
// Ship follows mouse X, fixed at bottom
ship.position.x = mouseX;
ship.position.y = 360;
// Randomly spawn obstacles from top
if(random(0,1) > 0.92){ // 8% chance each frame
let x = random(0,width); // Random X position
let y = 10; // Start at top
let o = createSprite(x,y,12,12); // Create obstacle sprite
o.velocity.y = random(2,3); // Fall speed
o.life = 2000; // Remove after 2000 frames
allObstacles.add(o); // Add to group
}
// Check collisions for each obstacle
for(let i = 0; i < allObstacles.length; i++){
let obst = allObstacles.get(i);
ship.collide(obst, kollision); // Ship vs obstacle
allObstacles.collide(obst, obstKollision); // Obstacle vs obstacle
}
shots.collide(allObstacles, shothit); // Bullets vs obstacles
drawSprites(); // Draw all sprites
}
// When obstacles collide with each other
function obstKollision(o1, o2){
o1.velocity.y = 0; // Stop both obstacles
o2.velocity.y = 0;
}
// When bullet hits obstacle
function shothit(s, o){
s.remove(); // Remove bullet
//o.remove(); // Could destroy obstacle
o.velocity.y = -o.velocity.y; // Bounce obstacle upward
}
// When ship hits obstacle
function kollision(spr,obst){
textAlign(CENTER);
textSize(48);
text("DEAD", 200,200); // Game over message
}
// Shoot when any key pressed
function keyPressed(){
var m = createSprite(ship.position.x, ship.position.y, 20, 20); // Create bullet at ship
m.velocity.x = 0; // Straight up
m.velocity.y = -30; // Fast upward speed
m.life = 100; // Remove after 100 frames
shots.add(m); // Add to shots group
}