How to move a sprite towards a target
Jump to navigation Jump to search
To move a sprite at a constant speed towards a target, find the difference in X and Y, and normalize by multiplying by the desired speed divided by the total distance. Then simply add the normalized differences to the sprite position.
See also How to point a sprite at a target.
This example moves a sprite continuously towards the mouse.
clear sp = new Sprite sp.image = file.loadImage("/sys/pics/Wumpus.png") sp.x = 480 sp.y = 320 display(4).sprites.push sp speed = 10 // (pixels per frame) while true // (press Control-C to exit) dx = mouse.x - sp.x dy = mouse.y - sp.y dist = sqrt(dx*dx + dy*dy) if dist < speed then dist = speed sp.x = sp.x + dx * speed/dist sp.y = sp.y + dy * speed/dist yield end while