Group assistance

Link to Project

What I expect to happen: When the tiger sprite1 touches the hotdog food, I create a new sprite (sprite2) and add sprite2 to a group - that works! However I want sprite2 / sprite3… and so on to follow sprite1 on the screen as sprite1 moves around.
What actually happens: sprites 2 & 3 appear but either don’t move or continue to move away from the sprite1
What I’ve tried: adding all to a group, different movements, youtube…I know it is something simple but I can not place it

well i’m not to sure of what your looking for but here’s my modified code

//Create your sprites like normal
var food = createSprite(180, 100);
food.setAnimation("hotdog");
food.scale = 0.15;
var sprite1 = createSprite(100, 300);
sprite1.setAnimation("tiger");
sprite1.scale = 0.15;
// var sprite2 = createSprite(200, 300);
// sprite2.setAnimation("tiger");
// sprite2.scale = 0.15;
// sprite2.visible = 0;
// var sprite3 = createSprite(300, 300);
// sprite3.setAnimation("tiger");
// sprite3.scale = 0.15;
// sprite3.visible = 0;

//use the groups toolbox
//create a group by creating a variable
//you can create multiple groups
var group1 = createGroup();
function draw() {
  //create a background
  background("white");
  var px = sprite1.x;
  var py = sprite1.y;
  //draw sprites
  drawSprites();
  if (sprite1.isTouching(food)) {
    sprite1.x = randomNumber(1, 200);
    sprite1.y = 300;
    var placeholder = createSprite(-500, -500);
    placeholder.setAnimation("tiger");
    placeholder.scale = 0.15;
    group1.add(placeholder);
  }
  movement();
  var dx = sprite1.x - px;
  var dy = sprite1.y - py;
  if (sprite1.x !== px || sprite1.y !== py) {
    for (var i = 0; i < group1.length; i++) {
      var trail = group1[i];
      var cx = trail.x;
      var cy = trail.y;
      if (px !== cx || py !== cy) {
        trail.x = px - dx * (i + 20);
        trail.y = py - dy * (i + 20);
      }
      px = cx;
      py = cy;
    }
  }
}
//movement Function
function movement() {
  if (keyDown("left")) {
    sprite1.x = sprite1.x - 2;
  }
  if (keyDown("right")) {
    sprite1.x = sprite1.x + 2;
  }
  if (keyDown("up")) {
    sprite1.y = sprite1.y - 2;
  }
  if (keyDown("down")) {
    sprite1.y = sprite1.y + 2;
  }
}
// function groupMovement() {
//   if (sprite1.x < group1.x) {
//     group1.setVelocityXEach(-3);
//   } else {
//     group1.setVelocityXEach(3);
//   }
//   if (sprite1.y < group1.y) {
//     group1.setVelocityYEach(-3);
//   } else {
//     group1.setVelocityYEach(3);
//   }
// }

this will give you a conga line effect effectively creating a trail behind the player in any direction you can do pathfinding stuff as well if you wish for the new companion spawned in to reach the player… do specify if you want different behavior hope this helps

2 Likes

THANK YOU!
This is what we were looking for.