p5play

repository·main·Indexed 20 days ago

https://github.com/quinton-ashley/p5play

A JavaScript game engine version 3.35.5 that uses p5.js for graphics and Box2D for physics. It provides a Sprite class for creating game objects with support for dynamic, static, and kinematic physics types, custom colliders, sensors, and animations. The library includes utilities for applying forces, torque, and movement, as well as global configuration via the p5play object. Note: p5play has been succeeded by q5play for improved performance.

Tokens
12.6K
Snippets
54
Records
63
Agent score
23%

What's inside p5play

  1. Migrate to q5play for improved performance and features

    main
    The original p5play library has been succeeded by q5play. q5play is a next-generation upgrade designed to be more beginner-friendly and approximately 10x faster than the original p5play. For new projects or those looking for enhanced features and performance, it is recommended to use q5play instead of p5play.
  2. Initialize p5play with p5.js or q5.js

    main

    p5play requires either p5.js or q5.js to be loaded before it can be initialized. It also requires planck.js for its physics engine. If planck.js is not found in the global scope, p5play will attempt to require('./planck.min.js') if running in a Node-like environment.

    // Ensure p5.js or q5.js is loaded in your HTML/environment
    // Then include p5play.js
    // p5play will automatically attach itself to the p5 instance
  3. Handle Sprite Mouse Hover and Dragging

    main

    When world.mouseTracking is enabled, sprites can have their own mouse input object (of type _SpriteMouse). This allows you to detect if the mouse is interacting specifically with a sprite.

    Methods:

    • hovers(): Returns true on the first frame the mouse enters the sprite's area.
    • hovering(): Returns the number of frames the mouse has been over the sprite.
    • hovered(): Returns true on the first frame the mouse leaves the sprite's area.

    Note: The sprite's mouse object also inherits button and drag states from the global mouse object.

    // Assuming 's' is a sprite
    s.mouse.hovers();
    s.mouse.hovering();
    s.mouse.hovered();
  4. How `Ani` and `Anis` work together

    main

    In p5play, animations are managed through a hierarchy.

    • Ani is the individual animation object.
    • Anis is a container (like sprite.anis or group.anis) that holds multiple named Ani objects.

    Inheritance Pattern: When you set a property on an Anis object (like scale, offset, or frameDelay), that property is automatically applied to all Ani objects contained within it. This allows you to change the animation style for an entire group of sprites at once.

    // Setting a property on the Anis container affects all animations in that sprite/group
    sprite.anis.frameDelay = 6;
    sprite.anis.scale = 2;
  5. Use Group property propagation

    main

    In p5play, setting a property on a Group propagates that change to all sprites within that group and its subgroups.

    For example, setting group.width = 50 will set the width of every sprite in that group to 50. This also works for vector properties like velocity (via group.velocity.x = 10) and other common sprite properties.

    Note: Certain properties like ani, velocity, width, height, and diameter are excluded from this automatic propagation to allow for individual sprite customization.

  6. Understand InputDevice state values

    main

    The InputDevice class (and its subclasses like mouse) tracks input states using integer values. Understanding these values is key to using methods like presses(), released(), or holds():

    • -3: Input was pressed and released on the same frame.
    • -2: Input was released after being held.
    • -1: Input was released.
    • 0: Input is not pressed.
    • 1: Input was pressed.
    • >1: Input is still being pressed.
  7. Use update() and drawFrame() for Game Logic

    main

    p5play provides two primary lifecycle functions that run 60 times per second by default:

    1. update(): Use this for input handling and game logic. It runs before physics simulation and drawing.
    2. drawFrame(): Use this for drawing code. It runs after input handling, game logic, and physics simulation.

    If you are using p5.js in a global context, you can define these functions directly on the window object.

    function update() {
      // Logic here
    }
    
    function drawFrame() {
      // Drawing here
    }
  8. Configure p5play global settings via the p5play object

    main

    The p5play object contains global configuration and state for the current sketch. You can modify these properties to change engine behavior.

    Key configuration properties:

    • p5play.disableImages: If true, prevents loading of images (useful for debugging).
    • p5play.emojiScale: Scale factor for emoji-based images.
    • p5play.friendlyRounding: If true, eliminates some floating point errors in physics calculations.
    • p5play.storeDeletedGroupRefs: If true, keeps data for deleted groups accessible (default). Set to false to reduce memory usage.
    • p5play.snapToGrid: If true, snaps sprites to the nearest gridSize increment.
    • p5play.gridSize: The size of the grid cells for snapping.
    • p5play.renderStats: If true, displays FPS and sprite count on screen.
    • p5play.palettes: An array of color palettes.
  9. Handle collisions and overlaps in Groups

    main

    Groups can check for physical interactions with other Groups or Sprites using collides and overlaps.

    Collisions (Physical contact)

    • collides(target, callback): Returns true on the first frame the group collides with the target.
    • colliding(target, callback): Returns the number of frames the group has been colliding with the target (truthy if colliding).
    • collided(target, callback): Returns true on the first frame the group no longer overlaps with the target.

    Overlaps (Sensor contact)

    • overlaps(target, callback): Returns true on the first frame the group overlaps with the target.
    • overlapping(target, callback): Returns the number of frames the group has been overlapping with the target.
    • overlapped(target, callback): Returns true on the first frame the group no longer overlaps with the target.

    Note: If a callback is provided, it will be triggered during the interaction event.

    // Using a callback for collision
    group.collides(otherGroup, (spriteA, spriteB, contact) => {
      console.log('Collision detected!');
    });
    
    // Checking in a loop
    if (group.collides(otherGroup)) {
      // handle collision
    }
  10. Configure the World and Physics

    main

    The World class manages the physics simulation. A world object is created automatically by p5play.

    Key Properties

    • gravity: A vector {x, y} affecting all dynamic physics colliders.
    • timeScale: A multiplier for the simulation speed (default 1.0, range 0 to 2).
    • updateRate: The fixed update rate in Hertz (default 60).
    • meterSize: Represents the size of a meter in pixels (default 60). Adjusting this changes the simulated scale of the physics world.
    • autoStep: If true (default), the physics simulation is automatically stepped at the end of the draw loop.
    • velocityThreshold: The lowest velocity an object can have before it is considered at rest (sleeps).

    Methods

    • physicsUpdate(timeStep, velocityIterations, positionIterations): Manually advances the physics simulation. If called without arguments, it uses the default timeStep calculated from updateRate and timeScale.
    // Adjusting gravity
    world.gravity = { x: 0, y: 9.8 };
    
    // Changing simulation speed
    world.timeScale = 0.5; // Slow motion
    
    // Adjusting physics scale
    world.meterSize = 100;
  11. Control Sprite Movement and Velocity

    main

    You can move sprites using several different properties:

    • vel or velocity: A vector {x, y} representing the current velocity.
    • speed: A scalar value. Setting this updates the velocity based on the current direction.
    • direction: The angle of movement. Can be a number (radians) or a string (e.g., 'up', 'down', 'left', 'right', 'upRight').
    • heading: A string alias for direction (e.g., 'upLeft').
    • bearing: An angle used to indicate a target direction (does not move the sprite automatically; use with applyForce).
    sprite.vel = { x: 5, y: 0 };
    sprite.speed = 10;
    sprite.direction = 'up';
    sprite.heading = 'downRight';