UNPKG

pxt-common-packages

Version:
67 lines (57 loc) 2.69 kB
# follow Set a sprite to always move to the position of another target sprite. ```sig 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](/types/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. ```blocks 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 [unfollow](/reference/sprites/sprite/unfollow), [overlaps with](/reference/sprites/sprite/overlaps-with)