### Complete p5play Configuration Example Source: https://github.com/quinton-ashley/p5play/blob/main/_autodocs/configuration.md A comprehensive example demonstrating the setup of physics, rendering, camera, input, player, groups, and sprites within the `setup()` function. Includes basic game loop logic in `draw()`. ```javascript function setup() { createCanvas(800, 600); // === PHYSICS CONFIGURATION === world.gravity = {x: 0, y: 9.8}; world.timeScale = 1.0; world.updateRate = 60; world.meterSize = 60; world.velocityIterations = 8; world.positionIterations = 3; world.velocityThreshold = 0.19; world.allowSleeping = true; world.autoStep = true; // === RENDERING CONFIGURATION === p5play.renderStats = true; p5play.friendlyRounding = true; p5play.snapToGrid = false; p5play.emojiScale = 1; // === CAMERA CONFIGURATION === camera.zoom = 1; camera.on(); // === INPUT CONFIGURATION === mouse.cursor = "default"; mouse.holdThreshold = 12; // === CREATE PLAYER === player = new Sprite(400, 300, 30, 30, "DYNAMIC"); player.color = "blue"; player.friction = 0.5; player.bounciness = 0.2; player.autoDraw = true; player.autoUpdate = true; // === CREATE GROUPS === platforms = new Group(); platforms.physics = "STATIC"; platforms.color = "brown"; platforms.autoDraw = true; enemies = new Group(); enemies.physics = "DYNAMIC"; enemies.color = "red"; enemies.density = 5; // === CREATE SPRITES === // Create platforms, enemies, etc. } function draw() { background(220); // Game logic here // Monitor performance if renderStats enabled if (p5play.renderStats) { fill(0); text("FPS: " + frameRate().toFixed(1), 10, 20); } } ``` -------------------------------- ### Complete p5play Usage Example Source: https://github.com/quinton-ashley/p5play/blob/main/_autodocs/api-reference/sprite.md This example demonstrates a basic p5play setup including sprite creation, movement, collision detection, mouse interaction, and camera control. ```javascript function setup() { createCanvas(400, 400); } function draw() { background(220); // Create player sprite if (!player) { player = new Sprite(200, 200, 30, 30); player.color = "blue"; player.friction = 0.5; } // Movement player.vel.x = 0; if (kb.pressing("left")) player.vel.x = -5; if (kb.pressing("right")) player.vel.x = 5; if (kb.pressing("up")) player.vel.y = -5; if (kb.pressing("down")) player.vel.y = 5; // Collision detection if (player.collides(obstacle)) { player.fill = "red"; } else { player.fill = "blue"; } // Mouse interaction if (player.mouse.hovers()) { player.scale = 1.1; } else { player.scale = 1; } // Camera follows player camera.moveTo(player.x, player.y, 0.1); } ``` -------------------------------- ### Get Sprites at Position Examples Source: https://github.com/quinton-ashley/p5play/blob/main/_autodocs/api-reference/world.md Examples show how to get sprites at the mouse's current position, filter results to a specific group like 'platforms', or retrieve all sprites regardless of camera activity. ```javascript // Get sprites at mouse position let spritesAtMouse = world.getSpritesAt(mouseX, mouseY); ``` ```javascript // Get sprites in specific group let platformsAtPos = world.getSpritesAt(100, 100, platforms); ``` ```javascript // Get all sprites (including off-camera) let allAtPos = world.getSpritesAt(200, 300, allSprites, false); ``` -------------------------------- ### Basic Sprite Creation Example Source: https://github.com/quinton-ashley/p5play/blob/main/_autodocs/START_HERE.txt Demonstrates the fundamental way to create a new sprite instance. This is a common starting point for many game development tasks. ```javascript let sprite = new Sprite(); ``` -------------------------------- ### Advanced Tile Group Configuration Source: https://github.com/quinton-ashley/p5play/blob/main/_autodocs/api-reference/utilities.md This example demonstrates a common usage pattern for the Tiles class within a p5.js setup function. It shows how to define a level map, create the tile group, set its physics type, and then iterate through the tiles to apply specific colors based on their character representation. ```javascript function setup() { createCanvas(400, 400); // Define level layout let levelMap = \ XXXXXXXXXXXXXXXX X X X P X X E X XXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXX ; // Create tiles (X = wall, others ignored by default) let tileGroup = new Tiles(levelMap, 0, 0, 25, 25); tileGroup.physics = "STATIC"; // Can use different characters for different tile types for (let tile of tileGroup) { if (tile.tile === "W") { tile.color = "blue"; // Water } else if (tile.tile === "G") { tile.color = "green"; // Grass } } } ``` -------------------------------- ### Get Mouse Hovering Sprites Example Source: https://github.com/quinton-ashley/p5play/blob/main/_autodocs/api-reference/world.md An example showing how to retrieve sprites under the mouse cursor and apply a visual change, such as reducing opacity, to each hovered sprite. ```javascript let hovering = world.getMouseSprites(); for (let sprite of hovering) { sprite.opacity = 0.5; } ``` -------------------------------- ### Ray Cast Examples Source: https://github.com/quinton-ashley/p5play/blob/main/_autodocs/api-reference/world.md Shows how to perform a ray cast starting from a sprite or a specific position. The examples demonstrate casting a ray to the right from a player and casting from a coordinate to find the first enemy within a certain distance. ```javascript // Ray cast from sprite let hit = world.rayCast(player, 0, 500); // Cast right 500 pixels if (hit) { console.log("Hit sprite:", hit.idNum); } ``` ```javascript // Ray cast from position let firstEnemy = world.rayCast({x: 100, y: 100}, 90, 300); ``` -------------------------------- ### Complete Camera and Input Example Source: https://github.com/quinton-ashley/p5play/blob/main/_autodocs/api-reference/camera-and-input.md This example demonstrates setting up a player sprite, enemies, activating the camera, and handling player movement via keyboard and gamepad. It also shows how to smoothly follow the player with the camera and adjust zoom, with UI elements displayed after camera operations. ```javascript let player, camera, enemies; function setup() { createCanvas(800, 600); player = new Sprite(200, 200, 30, 30); enemies = new Group(); for (let i = 0; i < 5; i++) { enemies.push(new Sprite(random(800), random(600), 20, 20)); } // Activate camera camera.on(); } function draw() { background(220); // WASD movement with keyboard let moveX = 0; let moveY = 0; if (kb.pressing("w") || kb.pressing("arrowUp")) { moveY = -5; } if (kb.pressing("s") || kb.pressing("arrowDown")) { moveY = 5; } if (kb.pressing("a") || kb.pressing("arrowLeft")) { moveX = -5; } if (kb.pressing("d") || kb.pressing("arrowRight")) { moveX = 5; } // Apply movement player.vel.x = moveX; player.vel.y = moveY; // Gamepad support if (contros.length > 0) { let stick = contros[0].leftStick; player.vel.x = stick.x * 5; player.vel.y = stick.y * 5; } // Smooth camera follow camera.moveTo(player.x, player.y, 0.08); // Zoom with mouse wheel (if using p5.js wheel event) let zoomFactor = 1; if (mouse.pressing("left")) { zoomFactor = 0.8; // Zoom out while dragging } camera.zoom = lerp(camera.zoom, zoomFactor, 0.1); // Draw UI (after camera) camera.off(); fill(0); text("Position: " + player.x.toFixed(0) + ", " + player.y.toFixed(0), 10, 20); text("Zoom: " + camera.zoom.toFixed(2) + "x", 10, 40); text("Controllers: " + contros.length, 10, 60); camera.on(); } ``` -------------------------------- ### Use q5.js to Avoid Setup Function Scope Issues Source: https://github.com/quinton-ashley/p5play/wiki/FAQ If you prefer to avoid the p5.js setup function's scope limitations for auto-completion, consider using q5.js. This allows file-level variable declarations and auto-completion in any function. ```javascript new Q5(); let mySprite = new Sprite(); function draw() { mySprite.color = 'blue'; } ``` -------------------------------- ### p5play Global Object Access Examples Source: https://github.com/quinton-ashley/p5play/blob/main/_autodocs/types.md Examples demonstrating how to access properties and modify settings of the global `p5play` object. Shows retrieving the version and enabling render statistics. ```javascript console.log(p5play.version); console.log(p5play.spritesCreated); p5play.renderStats = true; ``` -------------------------------- ### Ray Cast All Examples Source: https://github.com/quinton-ashley/p5play/blob/main/_autodocs/api-reference/world.md Demonstrates using `rayCastAll` to get all sprites hit by a ray, ordered by distance. It also shows how to use a `limiter` function to stop the raycast when a specific condition, like hitting a 'wall' type sprite, is met. ```javascript // Get all hits in order of distance let hits = world.rayCastAll(player.pos, 45, 500); for (let sprite of hits) { console.log("Hit:", sprite); } ``` ```javascript // With limiter function let hits = world.rayCastAll( {x: 100, y: 100}, 0, 400, function(sprite) { // Stop ray if hit specific type return sprite.type === "wall"; } ); ``` -------------------------------- ### Physics Simulation Examples Source: https://github.com/quinton-ashley/p5play/blob/main/_autodocs/api-reference/world.md Demonstrates various ways to call `physicsUpdate`. Examples include using default parameters, setting a custom time step for slow motion, adjusting iteration counts for higher quality, and integrating the update into a manual game loop. ```javascript // Use default parameters world.physicsUpdate(); ``` ```javascript // Custom time step for slow motion world.physicsUpdate(1/120); ``` ```javascript // Custom iterations for quality world.physicsUpdate(1/60, 10, 5); ``` ```javascript // Manual control function draw() { background(220); if (world.autoStep) { world.autoStep = false; // Take control } // Do game logic // Step physics world.physicsUpdate(); } ``` -------------------------------- ### Animation Frame Creation Examples Source: https://github.com/quinton-ashley/p5play/blob/main/_autodocs/types.md Examples illustrating how to create animations using different AnimationFrame configurations. Shows creating animations from loaded images, sprite sheets, and a mix of both. ```javascript // From images new Ani(loadImage("a.png"), loadImage("b.png")); // From sprite sheet with frames new Ani(spriteSheet, [0, 0, 32, 32], [32, 0, 32, 32]); // Mixed let ani = new Ani( loadImage("frame1.png"), [0, 0, 32, 32], [32, 0, 32, 32] ); ``` -------------------------------- ### WheelJoint Motor Control Example Source: https://github.com/quinton-ashley/p5play/blob/main/_autodocs/api-reference/joints.md Example of enabling and setting the speed for a WheelJoint motor. ```javascript let suspension = new WheelJoint(carBody, wheel); suspension.speed = 5; suspension.enableMotor = true; ``` -------------------------------- ### JavaScript Example for update Source: https://github.com/quinton-ashley/p5play/blob/main/_autodocs/api-reference/group.md Example of calling the update method to update all sprites in a group. ```javascript group.update(); ``` -------------------------------- ### Input Button Usage Examples Source: https://github.com/quinton-ashley/p5play/blob/main/_autodocs/types.md Examples demonstrating how to use the InputButton types with keyboard, mouse, and controller input functions. Check for key presses or continuous pressing. ```javascript if (kb.pressing("w")) { player.vel.y = -5; } if (mouse.presses("left")) { console.log("Clicked"); } if (contros[0].pressing("a")) { console.log("A pressed"); } ``` -------------------------------- ### CSS Cursor Style Assignment Examples Source: https://github.com/quinton-ashley/p5play/blob/main/_autodocs/types.md Examples showing how to set the mouse cursor style using the CursorStyle type. These examples demonstrate changing the cursor to a pointer, grab hand, and crosshair. ```javascript mouse.cursor = "pointer"; mouse.cursor = "grab"; mouse.cursor = "crosshair"; ``` -------------------------------- ### Install p5play via HTML Source: https://github.com/quinton-ashley/p5play/blob/main/_autodocs/README.md Include p5play in your HTML file by adding script tags for q5.js and p5play.js. ```html ``` -------------------------------- ### Sprite Constructor Examples Source: https://github.com/quinton-ashley/p5play/blob/main/_autodocs/api-reference/sprite.md Demonstrates creating Sprite instances with various configurations, including default, specific dimensions, circular shapes, and using animations. ```javascript let player = new Sprite(); ``` ```javascript let box = new Sprite(100, 150, 40, 60, "STATIC"); ``` ```javascript let ball = new Sprite(200, 200, 30); ``` ```javascript let character = new Sprite("walkingAnimation", 50, 100); ``` -------------------------------- ### RopeJoint Usage Example Source: https://github.com/quinton-ashley/p5play/blob/main/_autodocs/api-reference/joints.md Basic example of creating a RopeJoint. Sprites can get closer but not farther apart than the rope allows. ```javascript let rope = new RopeJoint(anchor, swingSprite); // Sprites can't be farther apart than the rope allows ``` -------------------------------- ### World Configuration at Startup Source: https://github.com/quinton-ashley/p5play/blob/main/_autodocs/configuration.md Configure global world physics and rendering settings within the `setup()` function. This includes gravity, update rate, iteration counts, and rendering options. ```javascript function setup() { createCanvas(800, 600); // Configure world world.gravity = {x: 0, y: 10}; world.updateRate = 60; world.velocityIterations = 8; world.positionIterations = 3; // Configure rendering p5play.renderStats = true; p5play.snapToGrid = false; // Create sprites and groups // ... } ``` -------------------------------- ### Global Physics Constants Usage Example Source: https://github.com/quinton-ashley/p5play/blob/main/_autodocs/types.md Example showing how to assign global physics constants to sprite and group physics properties. Demonstrates setting a sprite to dynamic and a group to static physics. ```javascript sprite.physics = DYNAMIC; group.physics = STATIC; ``` -------------------------------- ### JavaScript Example for colliding Source: https://github.com/quinton-ashley/p5play/blob/main/_autodocs/api-reference/group.md Example of using the colliding method to get the number of frames any sprite has been colliding. ```javascript let frames = enemies.colliding(player); ``` -------------------------------- ### HingeJoint Motor Control Example Source: https://github.com/quinton-ashley/p5play/blob/main/_autodocs/api-reference/joints.md Example of configuring hinge anchor positions and controlling the motor for a HingeJoint. ```javascript let door = new HingeJoint(frame, door); door.offsetA = {x: 20, y: 0}; door.offsetB = {x: -20, y: 0}; // Motor control door.enableMotor = true; door.speed = 5; door.maxPower = 50; ``` -------------------------------- ### JavaScript Example for draw Source: https://github.com/quinton-ashley/p5play/blob/main/_autodocs/api-reference/group.md Example of calling the draw method to draw all sprites in a group. ```javascript group.draw(); ``` -------------------------------- ### Complete Tile-Based Game Example Source: https://github.com/quinton-ashley/p5play/blob/main/_autodocs/api-reference/utilities.md This snippet demonstrates how to set up a complete tile-based game. It includes creating platforms, player, enemies, and collectibles from a level string, handling player movement, jumping, basic enemy AI, and collision detection for collectibles. It also shows how to implement a game over state and restart functionality. ```javascript let player, enemies, collectibles, platforms; function setup() { createCanvas(640, 480); // Game level as tile map let level = " ################################ # # # C C P # # ========= ========= ======= # # # # C # # === # # # # E E # # =================================== "; // Create static platforms from tiles platforms = new Group(); // Parse level and create entities let lines = level.split('\n'); for (let y = 0; y < lines.length; y++) { let line = lines[y]; for (let x = 0; x < line.length; x++) { let char = line[x]; let pixelX = x * 20; let pixelY = y * 20; if (char === '#') { // Wall platforms.push(new Sprite(pixelX, pixelY, 20, 20, "STATIC")); } else if (char === '=') { // Platform platforms.push(new Sprite(pixelX, pixelY, 20, 20, "STATIC")); } else if (char === 'P') { // Player player = new Sprite(pixelX, pixelY, 15, 20); player.color = "blue"; } else if (char === 'E') { // Enemy let enemy = new Sprite(pixelX, pixelY, 15, 15); enemy.color = "red"; if (!enemies) enemies = new Group(); enemies.add(enemy); } else if (char === 'C') { // Collectible let coin = new Sprite(pixelX, pixelY, 8, 8); coin.color = "yellow"; if (!collectibles) collectibles = new Group(); collectibles.add(coin); } } } // Style platforms platforms.color = "brown"; platforms.physics = "STATIC"; world.gravity.y = 10; camera.on(); } function draw() { background(135, 206, 235); // Player movement player.vel.x = 0; if (kb.pressing("left")) player.vel.x = -4; if (kb.pressing("right")) player.vel.x = 4; // Jump if (kb.presses("space") && player.colliding(platforms)) { player.vel.y = -8; } // Enemy AI (simple back and forth) if (enemies) { for (let enemy of enemies) { if (Math.random() < 0.01) { enemy.vel.x = (Math.random() > 0.5 ? 1 : -1) * 2; } } } // Collectibles if (collectibles) { collectibles.overlaps(player, function(coin, player) { coin.delete(); }); } // Smooth camera camera.moveTo(player.x, player.y, 0.1); // UI camera.off(); fill(0); textSize(16); text("Controls: Arrow Keys or A/D, Space to Jump", 10, 20); text("Coins: " + (collectibles ? collectibles.length : 0), 10, 40); if (player.y > height + 50) { text("Game Over! Press R to restart", width/2 - 100, height/2); } camera.on(); } function keyPressed() { if (key === 'r' || key === 'R') { setup(); // Restart } } ``` -------------------------------- ### SliderJoint Motor Control Example Source: https://github.com/quinton-ashley/p5play/blob/main/_autodocs/api-reference/joints.md Example of enabling and setting the speed for a SliderJoint motor. ```javascript let piston = new SliderJoint(cylinder, rod); piston.enableMotor = true; piston.speed = 10; ``` -------------------------------- ### HingeJoint Pendulum Example Source: https://github.com/quinton-ashley/p5play/blob/main/_autodocs/api-reference/joints.md Demonstrates creating a pendulum using a HingeJoint. The pendulum bob can be pushed with the mouse. ```javascript let anchor, pendulum, joint; function setup() { createCanvas(400, 400); // Anchor point (static) anchor = new Sprite(200, 100, 10, 10, "STATIC"); anchor.color = "black"; // Pendulum bob pendulum = new Sprite(200, 250, 30, 30); pendulum.color = "blue"; // Create hinge joint joint = new HingeJoint(anchor, pendulum); joint.offsetA = {x: 0, y: 0}; joint.offsetB = {x: 0, y: -70}; } function draw() { background(220); // Push pendulum on click if (mouse.presses("left")) { pendulum.vel.x = (mouseX - pendulum.x) * 0.1; } } ``` -------------------------------- ### Create and Play Animations Source: https://github.com/quinton-ashley/p5play/blob/main/_autodocs/api-reference/animation.md Example of preloading images, setting up a canvas and sprite, creating a new animation with a frame delay, adding it to the sprite, and controlling animation changes based on input. ```javascript function preload() { // Load images img1 = loadImage("walk1.png"); img2 = loadImage("walk2.png"); img3 = loadImage("walk3.png"); img4 = loadImage("walk4.png"); } function setup() { createCanvas(400, 400); player = new Sprite(200, 200, 32, 32); // Create animation let walkAni = new Ani(img1, img2, img3, img4); walkAni.name = "walk"; walkAni.frameDelay = 5; // Add to sprite player.addAni(walkAni); } function draw() { background(220); // Control animation if (kb.pressing("right")) { player.changeAni("walk"); } else { player.changeAni("idle"); } } ``` -------------------------------- ### JavaScript Example for collides Source: https://github.com/quinton-ashley/p5play/blob/main/_autodocs/api-reference/group.md Example of using collides to check if any sprite in the group is colliding with the target. Includes an example with a callback function to handle collisions. ```javascript if (enemies.collides(player)) { console.log("Enemy hit player"); } enemies.collides(walls, function(enemy, wall) { enemy.vel.x *= -1; // Bounce }); ``` -------------------------------- ### Play Animation Source: https://github.com/quinton-ashley/p5play/blob/main/_autodocs/api-reference/animation.md Starts playing the animation. Can specify a starting frame. Returns a promise that resolves when the animation completes. ```javascript await ani.play(); // Start from current frame await ani.play(0); // Start from first frame // Wait for animation to complete ani.play(0).then(() => { console.log("Animation finished"); }); ``` -------------------------------- ### JavaScript Example for overlaps Source: https://github.com/quinton-ashley/p5play/blob/main/_autodocs/api-reference/group.md Example of using overlaps to check if any sprite in the group is overlapping with the target. Includes an example with a callback function to handle overlaps. ```javascript if (coins.overlaps(player)) { console.log("Player near coins"); } coins.overlaps(player, function(coin, player) { coin.delete(); }); ``` -------------------------------- ### RopeJoint Pulley System Example Source: https://github.com/quinton-ashley/p5play/blob/main/_autodocs/api-reference/joints.md Illustrates a pulley system using a RopeJoint to connect two weights. The RopeJoint acts as the rope. ```javascript let pulley1, pulley2, weight1, weight2, joint; function setup() { createCanvas(400, 400); // Pulleys (static) pulley1 = new Sprite(100, 50, 20, 20, "STATIC"); pulley2 = new Sprite(300, 50, 20, 20, "STATIC"); // Weights weight1 = new Sprite(100, 200, 30, 30); weight2 = new Sprite(300, 150, 30, 30); // Distance joint acts like rope joint = new RopeJoint(weight1, weight2); } function draw() { background(220); } ``` -------------------------------- ### GrabberJoint Usage Example Source: https://github.com/quinton-ashley/p5play/blob/main/_autodocs/api-reference/joints.md Example of creating a GrabberJoint to attach two sprites. ```javascript let grabbed = new GrabberJoint(player, pickedUpSprite); ``` -------------------------------- ### Color Type Usage Example Source: https://github.com/quinton-ashley/p5play/blob/main/_autodocs/types.md Shows how to assign different color formats to sprite properties. ```javascript sprite.color = "red"; sprite.fill = "#FF0000"; sprite.stroke = color(0, 0, 0); sprite.textColor = "white"; ``` -------------------------------- ### Basic Java "Hello World" Source: https://github.com/quinton-ashley/p5play/wiki/Developer-Log A standard Java program to print 'Hello World!' to the console. This example illustrates the boilerplate code often required in Java for simple output. ```java class MyClass { public static void main(String[] args) { System.out.print("Hello World!"); } } ``` -------------------------------- ### p5play Global Mode Initialization Source: https://github.com/quinton-ashley/p5play/wiki/Developer-Log Initialize p5play in global mode by creating a new Q5 instance at the top of your sketch. Any code that would normally go in preload can follow, and setup will run after loading is complete. ```javascript new Q5() // preload code here function setup() { // setup code here } ``` -------------------------------- ### Joint Constructor Example Source: https://github.com/quinton-ashley/p5play/blob/main/_autodocs/api-reference/joints.md Demonstrates the recommended way to create a joint using a specific joint class like GlueJoint, as opposed to the base Joint class. ```javascript let joint = new Joint(spriteA, spriteB); // Recommended let joint = new GlueJoint(spriteA, spriteB); ``` -------------------------------- ### JavaScript Example for postDraw Source: https://github.com/quinton-ashley/p5play/blob/main/_autodocs/api-reference/group.md Example of calling the postDraw method, which is called after all sprites in the group are drawn. ```javascript group.postDraw(); ``` -------------------------------- ### HingeJoint Swinging Door Example Source: https://github.com/quinton-ashley/p5play/blob/main/_autodocs/api-reference/joints.md Demonstrates a swinging door using a HingeJoint. The door can be pushed with the mouse. ```javascript let frame, door, hinge; function setup() { createCanvas(400, 400); // Door frame (static) frame = new Sprite(150, 200, 10, 200, "STATIC"); // Door door = new Sprite(200, 200, 100, 200); door.color = "brown"; // Hinge joint at top hinge = new HingeJoint(frame, door); hinge.offsetA = {x: 0, y: -100}; hinge.offsetB = {x: -50, y: -100}; } function draw() { background(220); // Push door with mouse if (mouse.pressing("left")) { door.applyForce(5); } } ``` -------------------------------- ### Configure VSCode for p5play Auto-completion Source: https://github.com/quinton-ashley/p5play/wiki/FAQ Install necessary type definitions and create a jsconfig.json file to enable auto-completion for p5play and p5.js in Visual Studio Code. ```json { "compilerOptions": { "target": "ESNext" }, "typeAcquisition": { "include": ["node_modules/q5", "node_modules/p5play"] } } ``` -------------------------------- ### Basic Physics Setup with Gravity and Ground Source: https://github.com/quinton-ashley/p5play/blob/main/_autodocs/api-reference/world.md Sets up a canvas, applies global gravity to the y-axis, creates a static ground sprite, and a dynamic ball sprite that falls due to gravity. The ball resets its position if it goes below the canvas height. ```javascript function setup() { createCanvas(400, 400); // Set global gravity world.gravity.y = 10; // Create ground ground = new Sprite(200, 380, 400, 40, "STATIC"); ground.color = "brown"; // Create falling object ball = new Sprite(200, 50, 20, 20, "DYNAMIC"); ball.color = "red"; ball.bounciness = 0.8; } function draw() { background(220); // Ball falls due to gravity if (ball.y > height) { ball.y = 50; // Reset ball.vel = {x: 0, y: 0}; } } ``` -------------------------------- ### HingeJoint Motor-Driven Wheel Example Source: https://github.com/quinton-ashley/p5play/blob/main/_autodocs/api-reference/joints.md Demonstrates a motor-driven wheel using a HingeJoint. The wheel's speed can be controlled with keyboard input. ```javascript let axle, wheel, motorJoint; function setup() { createCanvas(400, 400); // Axle (static) axle = new Sprite(200, 200, 20, 20, "STATIC"); // Wheel wheel = new Sprite(200, 200, 60, 60); wheel.color = "gray"; // Hinge joint with motor motorJoint = new HingeJoint(axle, wheel); motorJoint.enableMotor = true; motorJoint.maxPower = 100; } function draw() { background(220); // Control wheel speed with keyboard if (keyboard.pressing("right")) { motorJoint.speed = 10; } else if (keyboard.pressing("left")) { motorJoint.speed = -10; } else { motorJoint.speed = 0; } text("Motor Speed: " + motorJoint.speed.toFixed(1), 10, 20); } ``` -------------------------------- ### Physics Type String Usage Example Source: https://github.com/quinton-ashley/p5play/blob/main/_autodocs/types.md Demonstrates creating sprites with different physics types and assigning physics types to existing sprites. ```javascript let player = new Sprite(x, y, 30, 30, "DYNAMIC"); let ground = new Sprite(x, y, 400, 50, "STATIC"); let platform = new Sprite(x, y, 100, 20, "KINEMATIC"); sprite.physics = "DYN"; ``` -------------------------------- ### DistanceJoint Spring Connection Example Source: https://github.com/quinton-ashley/p5play/blob/main/_autodocs/api-reference/joints.md Shows how to create a spring-like connection between two sprites using a DistanceJoint with springiness and damping. ```javascript let sprite1, sprite2, spring; function setup() { createCanvas(400, 400); sprite1 = new Sprite(100, 200); sprite2 = new Sprite(300, 200); // Distance joint with spring spring = new DistanceJoint(sprite1, sprite2); spring.springiness = 0.6; // Bouncy spring spring.damping = 0.3; // Some damping } function draw() { background(220); // Move sprites apart to test spring if (keyboard.pressing("left")) { sprite1.vel.x = -5; } if (keyboard.pressing("right")) { sprite2.vel.x = 5; } } ``` -------------------------------- ### Animation with Sprite Sheets Source: https://github.com/quinton-ashley/p5play/blob/main/_autodocs/api-reference/animation.md Example of creating an animation from a sprite sheet by defining the coordinates and dimensions for each frame. ```javascript function preload() { spriteSheet = loadImage("character-spritesheet.png"); } function setup() { createCanvas(400, 400); player = new Sprite(200, 200, 32, 32); // Create animation from sprite sheet frames let walk = new Ani( spriteSheet, [0, 0, 32, 32], // Frame 1: x, y, w, h [32, 0, 32, 32], // Frame 2 [64, 0, 32, 32], // Frame 3 [96, 0, 32, 32] // Frame 4 ); player.addAni(walk); } ``` -------------------------------- ### Cardinal Direction String Usage Example Source: https://github.com/quinton-ashley/p5play/blob/main/_autodocs/types.md Demonstrates setting sprite heading using various valid string formats, including case-insensitive and flexible options. ```javascript sprite.heading = "up"; sprite.heading = "upRight"; sprite.heading = "left"; sprite.heading = "DOWN_RIGHT"; // Flexible format sprite.heading = "north-east"; // Works too ``` -------------------------------- ### play(frame?) Source: https://github.com/quinton-ashley/p5play/blob/main/_autodocs/api-reference/animation.md Plays the animation starting from the specified frame. Returns a promise that resolves when the animation completes. ```APIDOC ## play(frame?) ### Description Plays the animation starting from the specified frame. Returns a promise that resolves when the animation completes. ### Method `play(frame?: number): Promise` ### Parameters #### Path Parameters - **frame** (number) - Optional - The frame to start playing from. ### Request Example ```javascript await ani.play(); // Start from current frame await ani.play(0); // Start from first frame // Wait for animation to complete ani.play(0).then(() => { console.log("Animation finished"); }); ``` ``` -------------------------------- ### Creating a GlueJoint Source: https://github.com/quinton-ashley/p5play/blob/main/_autodocs/api-reference/joints.md Example of creating a GlueJoint to rigidly connect two sprites, making them move as a single unit. ```javascript let glue = new GlueJoint(wheel, axle); ``` -------------------------------- ### Vector Type Usage Example Source: https://github.com/quinton-ashley/p5play/blob/main/_autodocs/types.md Demonstrates assigning values to sprite properties using the Vector type. ```javascript sprite.vel = {x: 5, y: 0}; sprite.scale = {x: 2, y: 1}; world.gravity = {x: 0, y: 9.8}; ``` -------------------------------- ### JavaScript Example for overlapping Source: https://github.com/quinton-ashley/p5play/blob/main/_autodocs/api-reference/group.md Example of using the overlapping method to get the number of frames any sprite has been overlapping. ```javascript let frames = coins.overlapping(player); ``` -------------------------------- ### Get First Physics Fixture Source: https://github.com/quinton-ashley/p5play/blob/main/_autodocs/api-reference/sprite.md Retrieve the first fixture node from the physics body's linked list. ```javascript let firstFixture = sprite.fixture; ``` -------------------------------- ### Get Top-Most Sprite at Position Example Source: https://github.com/quinton-ashley/p5play/blob/main/_autodocs/api-reference/world.md Demonstrates how to get the topmost sprite at the mouse's current position and log its ID if a sprite is found. ```javascript let topSprite = world.getSpriteAt(mouseX, mouseY); if (topSprite) { console.log("Clicked on sprite:", topSprite.idNum); } ``` -------------------------------- ### Joint Type String Usage Example Source: https://github.com/quinton-ashley/p5play/blob/main/_autodocs/types.md Illustrates creating different types of joints by instantiating their respective classes, which implicitly sets the joint type. ```javascript let glue = new GlueJoint(a, b); // type = "glue" let distance = new DistanceJoint(a, b); // type = "distance" let hinge = new HingeJoint(a, b); // type = "hinge" ``` -------------------------------- ### Group-Based Behaviors in p5play Source: https://github.com/quinton-ashley/p5play/blob/main/_autodocs/api-reference/group.md Shows examples of applying common behaviors to all sprites within a group, such as moving towards a target, applying forces, checking multiple collisions with callbacks, and changing animations. ```javascript // Move all enemies toward player enemies.moveTowards(player.x, player.y, 0.5); // Apply force to all enemies.applyForce(10); // Check multiple collisions with callback enemies.collides(player, function(enemy, player) { enemy.color = "orange"; player.life--; }); // Change animation for all enemies.changeAni("attack"); ``` -------------------------------- ### Accessing Global Physics and Camera Instances Source: https://github.com/quinton-ashley/p5play/blob/main/_autodocs/api-reference/utilities.md Illustrates how to access global instances for physics simulation ('world') and camera control ('camera'). These are fundamental for managing game state and viewport. ```javascript // World and physics world // Physics simulation and queries // Camera camera // Viewport and zoom control ``` -------------------------------- ### Create and Use Groups Source: https://github.com/quinton-ashley/p5play/blob/main/_autodocs/api-reference/group.md Demonstrates how to create empty groups or groups with initial sprites. It also shows how to access the global `allSprites` group. ```javascript let enemies = new Group(); let platforms = new Group(platform1, platform2, platform3); for (let sprite of allSprites) { sprite.draw(); } ``` -------------------------------- ### JavaScript Example for overlapped Source: https://github.com/quinton-ashley/p5play/blob/main/_autodocs/api-reference/group.md Example of using the overlapped method to check if a group just stopped overlapping with a target. ```javascript if (detectArea.overlapped(player)) { // Just left detection area } ``` -------------------------------- ### Tiles Class Constructor Source: https://github.com/quinton-ashley/p5play/blob/main/_autodocs/api-reference/utilities.md Creates a group of sprites from a tile map string, useful for level design. Each character in the string represents a tile type, with spaces creating empty cells and line breaks starting new rows. ```APIDOC ## Tiles Class Constructor ### Description Creates a group of sprites from a tile map string, useful for level design and platformer games. ### Method ```typescript constructor(tiles: string, x: number, y: number, w: number, h: number) ``` ### Parameters #### Path Parameters - **tiles** (string) - Yes - Tile map string with characters representing different tiles - **x** (number) - Yes - Starting x position - **y** (number) - Yes - Starting y position - **w** (number) - Yes - Width of each tile in pixels - **h** (number) - Yes - Height of each tile in pixels ### Returns A Group containing all the tile sprites. ### Notes - Each character in the tile string represents a tile type - Spaces create empty cells (no sprite) - Line breaks (`\n`) start new rows - The function also returns the group (assignable) ### Example ```javascript let level = ` ############ # P # # T # ############ `; let tiles = new Tiles(level, 0, 0, 20, 20); tiles.physics = "STATIC"; tiles.color = "brown"; ``` ``` -------------------------------- ### JavaScript Example for overlap Source: https://github.com/quinton-ashley/p5play/blob/main/_autodocs/api-reference/group.md Example of using the deprecated overlap method to check for the first frame of an overlap. ```javascript if (collectibles.overlap(player)) { // Just overlapped } ``` -------------------------------- ### JavaScript Example for collided Source: https://github.com/quinton-ashley/p5play/blob/main/_autodocs/api-reference/group.md Example of using the collided method to check if a group just stopped colliding with a target. ```javascript if (group.collided(obstacle)) { // Just stopped colliding } ``` -------------------------------- ### JavaScript Example for collide Source: https://github.com/quinton-ashley/p5play/blob/main/_autodocs/api-reference/group.md Example of using the deprecated collide method to check for the first frame of a collision. ```javascript if (group.collide(walls)) { // Just collided } ``` -------------------------------- ### Load p5play from CDN Source: https://github.com/quinton-ashley/p5play/wiki/FAQ Use these CDN links if your network firewall blocks the p5play.org domain. This ensures the library can be loaded in your project. ```html ``` -------------------------------- ### splice(start, removalCount, ...sprites) Source: https://github.com/quinton-ashley/p5play/blob/main/_autodocs/api-reference/group.md Removes a specified number of sprites from the group starting at a given index, and optionally inserts new sprites at that position. ```APIDOC ## splice(start, removalCount, ...sprites) Removes and optionally adds sprites to the group. ```typescript splice(start: number, removalCount: number, ...sprites: Sprite[]): Sprite[] ``` ```javascript let removed = group.splice(0, 2, newSprite); ``` ``` -------------------------------- ### Basic p5play Game Loop Source: https://github.com/quinton-ashley/p5play/blob/main/_autodocs/README.md Sets up a canvas, creates a player sprite and a group of static obstacles, and applies gravity. The draw loop handles player movement based on keyboard input and changes player color on collision with obstacles. ```javascript function setup() { createCanvas(400, 400); // Create player player = new Sprite(200, 200, 30, 30); player.color = "blue"; // Create obstacles obstacles = new Group(); obstacles.physics = "STATIC"; obstacles.color = "gray"; // Setup gravity world.gravity.y = 10; } function draw() { background(220); // Player control if (kb.pressing("left")) player.vel.x = -5; if (kb.pressing("right")) player.vel.x = 5; // Collision response if (player.collides(obstacles)) { player.color = "red"; } else { player.color = "blue"; } } ``` -------------------------------- ### Sprite Initialization with Animation Source: https://github.com/quinton-ashley/p5play/wiki/Change-Log Shows two ways to initialize a sprite with an animation: directly in the constructor or by assigning the animation after creation. ```javascript // image/ani in constructor let ball = new Sprite(ballAnimation); // image/ani added outside the constructor let ball = new Sprite(); ball.ani = ballAnimation; ``` -------------------------------- ### Group Constructor Properties Source: https://github.com/quinton-ashley/p5play/blob/main/_autodocs/api-reference/group.md Shows how to set properties directly when creating a group or by assigning to a predefined array. ```javascript let staticSprites = new Group(); staticSprites.physics = "STATIC"; let myGroup = new Group(...spriteArray); ``` -------------------------------- ### Creating and Managing Groups in p5play Source: https://github.com/quinton-ashley/p5play/blob/main/_autodocs/api-reference/group.md Demonstrates how to create groups, add sprites to them, and apply properties and collision checks to entire groups. This is useful for organizing game objects and managing their interactions. ```javascript function setup() { createCanvas(400, 400); // Create groups enemies = new Group(); platforms = new Group(); powerups = new Group(); // Create some sprites in groups for (let i = 0; i < 5; i++) { let enemy = new Sprite(random(width), random(height), 20, 20); enemies.add(enemy); } } function draw() { background(220); // Apply properties to entire group enemies.color = "red"; platforms.physics = "STATIC"; powerups.color = "yellow"; // Check collisions if (player.collides(enemies)) { console.log("Game Over!"); } if (player.overlaps(powerups)) { powerups.delete(); } } ``` -------------------------------- ### Accessing Global Input Instances Source: https://github.com/quinton-ashley/p5play/blob/main/_autodocs/api-reference/utilities.md Shows how to access global instances for mouse ('mouse'), keyboard ('kb' or 'keyboard'), touch ('touches'), and controller ('contros' or 'controllers') input. ```javascript // Input mouse // Mouse position and buttons kb // Keyboard state keyboard // Alias for kb touches // Array of touch points contros // Array of connected controllers controllers // Alias for contros ``` -------------------------------- ### Initialize Canvas with Presets and WebGL Mode Source: https://github.com/quinton-ashley/p5play/wiki/Change-Log When using p5play canvas presets with the 'webgl' renderer, specify the preset before the mode parameter. ```javascript new Canvas(400, 400, 'fullscreen', 'webgl'); ``` -------------------------------- ### Control Current Animation Source: https://github.com/quinton-ashley/p5play/blob/main/_autodocs/api-reference/sprite.md Get a reference to the currently playing animation or set a new animation for the sprite. ```javascript let current = sprite.animation; sprite.animation = sprite.animations.idle; ``` -------------------------------- ### Configure Multi-State Animations Source: https://github.com/quinton-ashley/p5play/blob/main/_autodocs/api-reference/animation.md Set up a sprite with multiple distinct animations representing different states (idle, walk, jump). Configure properties like looping and frame delay for each state. ```javascript let sprite = new Sprite(200, 200, 40, 40); // Create state machine with animations sprite.addAni("idle", idle1, idle2, idle3); sprite.addAni("walk", walk1, walk2, walk3, walk4); sprite.addAni("jump", jumpUp, jumpDown); sprite.addAni("fall", falling); // Configure each animation sprite.anis.idle.looping = true; sprite.anis.idle.frameDelay = 6; sprite.anis.walk.looping = true; sprite.anis.walk.frameDelay = 4; sprite.anis.jump.looping = false; sprite.anis.jump.frameDelay = 3; sprite.anis.jump.onComplete = function() { sprite.changeAni("fall"); }; ``` -------------------------------- ### Get Planck Physics Body Source: https://github.com/quinton-ashley/p5play/blob/main/_autodocs/api-reference/sprite.md Access the underlying Planck physics body object associated with the sprite. ```javascript let planckBody = sprite.body; ``` -------------------------------- ### Get Sprite Mass Source: https://github.com/quinton-ashley/p5play/blob/main/_autodocs/api-reference/sprite.md Retrieve the sprite's mass, which is a read-only value calculated from its density and size. ```javascript let m = sprite.mass; ``` -------------------------------- ### Get Group ID Source: https://github.com/quinton-ashley/p5play/blob/main/_autodocs/api-reference/group.md Shows how to retrieve the unique ID number of a group, useful for debugging purposes. ```javascript console.log(`Group #${group.idNum}`); ``` -------------------------------- ### Camera and Input API Reference Source: https://github.com/quinton-ashley/p5play/blob/main/_autodocs/DOCUMENTATION_SUMMARY.txt Documentation for the Camera and Input systems, handling viewport and user interactions. ```APIDOC ## Camera and Input API Reference ### Description Documentation for the Camera and Input systems, handling viewport and user interactions. ### Camera Properties - **x** (number) - The x-coordinate of the camera. - **y** (number) - The y-coordinate of the camera. - **zoom** (number) - The zoom level of the camera. ### Input Methods - **mouse.presses(button)**: Returns true if the specified mouse button was just pressed. - **kb.pressing(key)**: Returns true if the specified key is currently being pressed. - **controller.getAxis(axis)**: Returns the value of the specified analog stick axis. ### Examples ```javascript camera.moveTo(sprite.x, sprite.y); if (mouse.presses('left')) { console.log('Left mouse button pressed'); } if (kb.pressing('space')) { console.log('Space bar is pressed'); } ``` ``` -------------------------------- ### Create a Tile-Based Level with p5play Source: https://github.com/quinton-ashley/p5play/blob/main/_autodocs/api-reference/utilities.md This snippet demonstrates how to define a tile-based level using a string map and create corresponding sprite groups for walls, the player, enemies, and collectibles. It also shows basic input handling and camera control. ```javascript function setup() { createCanvas(600, 400); // Define a tile-based level let levelMap = ` ==================== = P = = E1 E2 = =================== =================== = C T C = =================== `; // Create tile groups for different element types let walls = createTiles(levelMap.replace(/[^=]/g, ' '), 0, 0, 25, 25); walls.physics = "STATIC"; walls.color = "gray"; // Create player player = new Sprite(150, 50, 20, 30); player.color = "blue"; player.tile = "P"; // Create enemies (search for 'E' in tile map) enemies = new Group(); // Create collectibles (search for 'C' in tile map) collectibles = new Group(); // Camera follows player camera.on(); } function draw() { background(200); // Input handling if (kb.pressing("left")) player.vel.x = -5; if (kb.pressing("right")) player.vel.x = 5; if (kb.pressing("up") && player.colliding(allSprites)) { player.vel.y = -10; } // Camera follow camera.moveTo(player.x, player.y, 0.1); // Collectible pickup for (let collectible of collectibles) { if (player.overlaps(collectible)) { collectible.delete(); } } // UI (draw with camera off) camera.off(); fill(0); text("Score: " + (1000 - collectibles.length * 100), 10, 20); camera.on(); } ``` -------------------------------- ### Shape Type String Usage Example Source: https://github.com/quinton-ashley/p5play/blob/main/_autodocs/types.md Shows how to set the collider shape for a sprite using string values. ```javascript sprite.shape = "circle"; sprite.shape = "box"; sprite.shape = "polygon"; ```