Group sprites following other sprites

(Game Lab - Code.org)
My student is trying to create sprites in a group following another sprite, neither of us have any clue on how to create this behavior
We have tried whatever we could think of, nothing has worked.

Hello @su8scri88le,

I would recommend checking out this topic if this thread does not satisfy what you are looking for feel free to update the thread to give a more specific case of what type of following you are looking for

Varrience

This is not the type of behavior we are looking for, I apologize for not being more clear in my previous post. What we are looking for is code to make a sprite move toward another one, as an attacking enemy.

You could try this:

  
  var dx = targetX+randomNumber(10,30) - creature.x;
  var dy = targetY+randomNumber(10,30) - creature.y;
  var angle = Math.atan2(dx,dy);
  creature.x += speed*Math.sin(angle);
  creature.y += speed*Math.cos(angle);

where targetX and targetY are the points your enemy wants to move toward. dx is the distance x and dy is the distance y, this takes those values and finds the angle to the target and moves in that direction

1 Like

i need this to work with groups so i can spawn multiple of them. Is there any way to do that?

Use the for statement and add each sprite to the group, then every frame loop through every sprite in that group and apply the movement script to it.


var sprites = createGroup();
var spriteAmount = 10;
var defaultSpeed = 2;
for (var i = 0; i < spriteAmount; i++){
  
  var sprite = createSprite(randomNumber(0,400),randomNumber(0,400)); // makes a sprite at a random position at the screen
  sprite.scale = 0.5;
  sprites.add(sprite); //adds it to the group
  
}


function draw() {
  background("white");
  for (var i = 0; i < sprites.length; i++){ // starts i at 0 and as long as i < the amount of sprites in the group increases i.
     
    var thisSprite = sprites.get(i); //makes a variable for the current sprite in the group
    
    move(thisSprite, camera.mouseX, camera.mouseY, defaultSpeed); //calls the movement script 
    
  }
  
  
  drawSprites();
}
//previous code:
function move(sprite, targetX, targetY, speed){
  var dx = targetX+randomNumber(10,30) - sprite.x;
  var dy = targetY+randomNumber(10,30) - sprite.y;
  var angle = Math.atan2(dx,dy);
  sprite.x += speed*Math.sin(angle);
  sprite.y += speed*Math.cos(angle);
  
  
}