Multiple Followers

back

Notes

The object will follow wherever you point.

This example defines a Follower that takes a target as one of its parameters. The Follower updates its velocity every frame to move it in the direction of the target. It stops when it is within MIN_DISTANCE.

Each Follower (except the first one) targets the Follower in front of it. The first follower still targets the pointer position.

Source

/* @pjs preload="player.png"; */

PImage player;

Follower[] followers;
int NUMBER_OF_FOLLOWERS = 10;

// Setup the example
void setup(){
  size(640, 480);
  
  imageMode(CENTER);
  
  // Load images
  player = loadImage("player.png");
  
  // Create 5 followers, each one following the one ahead of it
  // The first one will follow the mouse pointer
  followers = new Follower[NUMBER_OF_FOLLOWERS];
  Follower lastFollower = null;
  for(int i = 0; i < followers.length; i++){
    followers[i] = new Follower(player, width/2 + i * 32, height/2, lastFollower);
    lastFollower = followers[i];
  }
}

void draw(){
  background(#4488cc);
  
  for(Follower f : followers){
    f.display();
  }
}

class Follower{
  // Save the target that this Follower will follow
  Follower other;
  PImage img;
  float follower_x;
  float follower_y;
  float velocity_x;
  float velocity_y;
  
  // Define constants that affect motion
  float MAX_SPEED = 4;
  float MIN_DISTANCE = 32;
  
  // Follower constructor
  Follower(PImage img, int x, int y, Follower other){
    this.img = img;
    follower_x = x;
    follower_y = y;
    this.other = other;
  }
  
  void display(){
    float x = mouseX;
    float y = mouseY;
    if(other != null){
      x = other.follower_x;
      y = other.follower_y;
    }
    
    // Calculate distance to target
    float distance = dist(follower_x, follower_y, x, y);
    
    // If the distance > MIN_DISTANCE then move
    if(distance > MIN_DISTANCE){
      // Calculate the angle to the target
      float rotation = atan2(y - follower_y, x - follower_x);
      
      // Calculate velocity vector based on rotation and this.MAX_SPEED
      velocity_x = cos(rotation) * MAX_SPEED;
      velocity_y = sin(rotation) * MAX_SPEED;
      
    }else{
      velocity_x = velocity_y = 0;
    }
    
    follower_x += velocity_x;
    follower_y += velocity_y;
    
    image(img, follower_x, follower_y);
  }
}

Warning: Cannot load module "http" because required module "raphf" is not loaded in Unknown on line 0