follow

Set a sprite to always move to the position of another target sprite.

sprites.create(null).follow(null, 0)

When you set a sprite to follow a target sprite, it will move toward the target by “chasing” it with a certain speed. If the sprite can reach the target before it moves again, the sprite will stop and occupy the same location as the target sprite. When not moving, the sprites overlap each other at their center locations.

Parameters

  • target: the target sprite to follow.
  • speed: the maximum chase speed after accelerating, in pixels per second, when moving toward the target sprite.
  • turnRate: (optional) the time to take in making a turn to toward the target sprite. For example, using the default rate, 400, the sprite will reach speed in 125 milleseconds when turing 180 degrees to chase the target.

Example

Create 2 sprites. Set the second sprite to follow the first one. Every second, randomly change the position of the first sprite on the screen so that the second sprite will keep chasing it.

let mySprite = sprites.create(img`
    . . . . . . . . . . . . . . . . 
    . . . . . . . . . . . . . . . . 
    . . . . . 7 7 7 7 7 7 . . . . . 
    . . . 7 7 7 7 7 7 7 7 7 7 . . . 
    . . . 7 7 7 7 7 7 7 7 7 7 . . . 
    . . 7 7 7 7 7 7 7 7 7 7 7 7 . . 
    . . 7 7 7 7 7 7 7 7 7 7 7 7 . . 
    . . 7 7 7 7 7 7 7 7 7 7 7 7 . . 
    . . 7 7 7 7 7 7 7 7 7 7 7 7 . . 
    . . 7 7 7 7 7 7 7 7 7 7 7 7 . . 
    . . 7 7 7 7 7 7 7 7 7 7 7 7 . . 
    . . . 7 7 7 7 7 7 7 7 7 7 . . . 
    . . . 7 7 7 7 7 7 7 7 7 7 . . . 
    . . . . . 7 7 7 7 7 7 . . . . . 
    . . . . . . . . . . . . . . . . 
    . . . . . . . . . . . . . . . . 
    `, SpriteKind.Player)
let mySprite2 = sprites.create(img`
    . . . . . . . . . . . . . . . . 
    . . . . . . . . . . . . . . . . 
    . . . . . 5 5 5 5 5 5 . . . . . 
    . . . 5 5 5 5 5 5 5 5 5 5 . . . 
    . . . 5 5 5 5 5 5 5 5 5 5 . . . 
    . . 5 5 5 5 5 5 5 5 5 5 5 5 . . 
    . . 5 5 5 5 5 5 5 5 5 5 5 5 . . 
    . . 5 5 5 5 5 5 5 5 5 5 5 5 . . 
    . . 5 5 5 5 5 5 5 5 5 5 5 5 . . 
    . . 5 5 5 5 5 5 5 5 5 5 5 5 . . 
    . . 5 5 5 5 5 5 5 5 5 5 5 5 . . 
    . . . 5 5 5 5 5 5 5 5 5 5 . . . 
    . . . 5 5 5 5 5 5 5 5 5 5 . . . 
    . . . . . 5 5 5 5 5 5 . . . . . 
    . . . . . . . . . . . . . . . . 
    . . . . . . . . . . . . . . . . 
    `, SpriteKind.Player)
mySprite2.follow(mySprite, 50,)
game.onUpdateInterval(1000, function () {
    mySprite.setPosition(randint(0, scene.screenWidth()), randint(0, scene.screenHeight()))
})

See also

overlaps with