Skip to content
TheChatArchiveThe Chat Archive
o1-preview-2024-09-12· OpenAIAi2 WildChat-4.8M (AI2)

Create a p5.js fish that follows the mouse pointer. The fish is defined by a series of…

  1. User

    Create a p5.js fish that follows the mouse pointer. The fish is defined by a series of circles. Each circle has children at certain offsets and all the circles collide with each other. For a fish shape for instance there is a small circle at the front (nose) larger circle defining the mid section with three child circles, one on either side for fins, then continuing down the chain, a small circle where the tail narrows and two larger circles connected to that side by side to form the tail. Then draw the fish by drawing a smooth line around the external points of the circles. The fish shouldn't look jointed but instead smooth. Each circle follows its parent circles and circles cannot intersect. The rigidity of this following is an elasticity parameter. The first circle smoothly glides towards the mouse pointer so that the fish follows. Each circle should always move in its direction and turn direction with direction elasticity towards its parent circle. The fish's outline should be smooth, not jagged, also apply a friction parameter to keep things from spiraling out of hand. Fill in the body of the fish and make the outline very smooth by finding a shape that contains all of the smaller circles within it then rendering it with bezier curves, (like shrink-wrapping all of the circles). this can be controlled by a shrink parameter, where a value of 1 tightly fits all circles and a value of 0 tries to minimize bending. If the fish is at the mouse pointer it shouldn't spin around or malfunction, nor should the fish jerk back and forth. This should be generalizeable to any "creature", for example a centipede or a snake could be defined with different circles.

  2. Assistant

    Here is a p5.js sketch that creates a fish composed of circles which follows the mouse pointer. The fish is constructed using circles connected in a hierarchical manner, and its outline is smoothly rendered using bezier curves to create a shrink-wrapped effect around the circles.

    You can run this code in the p5.js web editor.

    let fish;
    
    function setup() {
      createCanvas(windowWidth, windowHeight);
      
      // Create the fish object
      fish = new Fish();
    }
    
    function draw() {
      background(220);
      
      // Update and draw the fish
      fish.update();
      fish.draw();
    }
    
    class Fish {
      constructor() {
        this.circles = [];
        this.elasticity = 0.1; // Controls how tightly the circles follow their parent
        this.friction = 0.9;   // Friction applied to velocities
        this.shrink = 0.5;     // Controls how tightly the outline fits around the circles (0 to 1)
    
        // Define the fish body structure
        // Nose circle
        let nose = new Circle(createVector(width/2, height/2), 15);
        this.circles.push(nose);
    
        // Midsection circle (parent: nose)
        let mid = new Circle(createVector(width/2, height/2 + 40), 30, nose);
        nose.children.push(mid);
        this.circles.push(mid);
    
        // Left fin (child of midsection)
        let leftFinOffset = createVector(-30, 0);
        let leftFin = new Circle(mid.position.copy().add(leftFinOffset), 10, mid, leftFinOffset);
        mid.children.push(leftFin);
        this.circles.push(leftFin);
    
        // Right fin (child of midsection)
        let rightFinOffset = createVector(30, 0);
        let rightFin = new Circle(mid.position.copy().add(rightFinOffset), 10, mid, rightFinOffset);
        mid.children.push(rightFin);
        this.circles.push(rightFin);
    
        // Tail narrow circle (child of midsection)
        let tailNarrowOffset = createVector(0, 40);
        let tailNarrow = new Circle(mid.position.copy().add(tailNarrowOffset), 15, mid, tailNarrowOffset);
        mid.children.push(tailNarrow);
        this.circles.push(tailNarrow);
    
        // Tail left fin (child of tail narrow)
        let tailLeftOffset = createVector(-15, 20);
        let tailLeft = new Circle(tailNarrow.position.copy().add(tailLeftOffset), 20, tailNarrow, tailLeftOffset);
        tailNarrow.children.push(tailLeft);
        this.circles.push(tailLeft);
    
        // Tail right fin (child of tail narrow)
        let tailRightOffset = createVector(15, 20);
        let tailRight = new Circle(tailNarrow.position.copy().add(tailRightOffset), 20, tailNarrow, tailRightOffset);
        tailNarrow.children.push(tailRight);
        this.circles.push(tailRight);
      }
    
      update() {
        // Update each circle's position
        for (let circle of this.circles) {
          circle.update(this.elasticity, this.friction);
        }
    
        // Handle collisions between circles to prevent overlap
        for (let i = 0; i < this.circles.length; i++) {
          for (let j = i + 1; j < this.circles.length; j++) {
            resolveCollision(this.circles[i], this.circles[j]);
          }
        }
      }
    
      draw() {
        // Draw the fish outline
        noStroke();
        fill(100, 150, 255);
    
        let outlinePoints = this.getOutlinePoints();
        beginShape();
        for (let pt of outlinePoints) {
          vertex(pt.x, pt.y);
        }
        endShape(CLOSE);
    
        // Optionally draw the circles for debugging
        // for (let circle of this.circles) {
        //   circle.draw();
        // }
      }
    
      getOutlinePoints() {
        // Collect edge points from circles
        let points = [];
        for (let circle of this.circles) {
          // Sample points around the circle's perimeter
          let numPoints = 8;
          for (let i = 0; i < numPoints; i++) {
            let angle = map(i, 0, numPoints, 0, TWO_PI);
            let x = circle.position.x + cos(angle) * circle.radius * this.shrink;
            let y = circle.position.y + sin(angle) * circle.radius * this.shrink;
            points.push(createVector(x, y));
          }
        }
    
        // Convex hull to order the points around the perimeter
        points = getConvexHull(points);
    
        return points;
      }
    }
    
    class Circle {
      constructor(position, radius, parent = null, offset = createVector(0, 0)) {
        this.position = position.copy();
        this.velocity = createVector(0, 0);
        this.radius = radius;
        this.parent = parent;
        this.children = [];
        this.offset = offset.copy();
      }
    
      update(elasticity, friction) {
        let target;
    
        if (this.parent) {
          // Target position is based on parent position plus offset
          target = p5.Vector.add(this.parent.position, this.offset);
        } else {
          // Nose circle moves towards the mouse
          target = createVector(mouseX, mouseY);
        }
    
        // Apply elasticity
        let force = p5.Vector.sub(target, this.position).mult(elasticity);
        this.velocity.add(force);
    
        // Apply friction
        this.velocity.mult(friction);
    
        // Update position
        this.position.add(this.velocity);
      }
    
      draw() {
        stroke(0);
        fill(255, 150);
        ellipse(this.position.x, this.position.y, this.radius * 2);
      }
    }
    
    function resolveCollision(c1, c2) {
      let diff = p5.Vector.sub(c1.position, c2.position);
      let dist = diff.mag();
      let minDist = c1.radius + c2.radius;
    
      if (dist < minDist && dist > 0) {
        // Move circles apart so they just touch
        let overlap = (minDist - dist) / 2;
        diff.normalize();
        c1.position.add(diff.copy().mult(overlap));
        c2.position.sub(diff.copy().mult(overlap));
      }
    }
    
    // Gift wrapping algorithm to get convex hull of points
    function getConvexHull(points) {
      // Find the leftmost point
      let start = points[0];
      for (let pt of points) {
        if (pt.x < start.x) {
          start = pt;
        }
      }
    
      let hull = [];
      let current = start;
      let prevAngle = 0;
      do {
        hull.push(current);
        let next = null;
        let nextAngle = 0;
        for (let pt of points) {
          if (pt == current) continue;
          let angle = atan2(pt.y - current.y, pt.x - current.x);
          let angleDiff = angle - prevAngle;
          if (angleDiff <= 0) angleDiff += TWO_PI;
    
          if (next == null || angleDiff < nextAngle) {
            next = pt;
            nextAngle = angleDiff;
          }
        }
        prevAngle = atan2(next.y - current.y, next.x - current.x);
        current = next;
      } while (current != start);
    
      return hull;
    }
    

    How It Works

    Fish Structure

    The fish is constructed using a Fish class that manages an array of Circle objects. Each Circle represents a part of the fish's body. The circles are connected hierarchically to form the fish's shape:

    • Nose: The front of the fish, moves towards the mouse pointer.
    • Midsection: Connected to the nose, represents the main body.
    • Fins: Two circles connected to the midsection, represent the side fins.
    • Tail Narrow: A smaller circle connected to the midsection, where the tail narrows.
    • Tail Fins: Two larger circles connected to the tail narrow circle, represent the tail fins.

    Movement and Elasticity

    • Elasticity: Controls how tightly each circle follows its target position (either the mouse or its parent's offset position).
    • Friction: Applied to each circle's velocity to dampen movement and prevent oscillations.

    Each circle calculates a force towards its target position (defined by its parent and offset) and updates its velocity and position accordingly.

    Collision Resolution

    To prevent the circles from intersecting, the resolveCollision function adjusts the positions of overlapping circles so that they just touch each other. This maintains the structural integrity of the fish and ensures a smooth outline.

    Drawing the Fish

    • Outline Points: The fish's outline is created by sampling points around the perimeter of each circle, scaled by the shrink parameter.
    • Convex Hull: The sampled points are ordered using the convex hull algorithm (gift wrapping) to create a smooth outer boundary around the fish.
    • Rendering: The ordered points are used to draw the fish's outline with the beginShape() and endShape(CLOSE) functions.

    Parameters

    • Elasticity (elasticity): Adjust this parameter to control how responsive the fish is to movements of its parent circles. A higher value makes the fish more rigid.
    • Friction (friction): Controls the damping of the movement. Higher friction slows down the movement and reduces oscillations.
    • Shrink (shrink): Determines how tightly the outline fits around the circles. A value of 1 fits tightly, while a value closer to 0 creates a looser, smoother shape.

    Generalization

    The same approach can be adapted to create different creatures like centipedes or snakes by modifying the structure of circles and their connections.

    Notes

    • The code uses a simple convex hull algorithm to order the outline points. For more complex shapes or better performance, consider using more advanced algorithms or libraries.
    • The draw() method in the Fish class can be modified to include textures or more detailed rendering.

    Run the Code

    To run the code, copy it into the p5.js web editor and press the Play button. Move your mouse around the canvas to see the fish follow the pointer smoothly.

    Feel free to adjust the parameters (elasticity, friction, shrink) in the Fish class constructor to see how they affect the fish's behavior.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.