How to move a sprite towards a target

From MiniScript Wiki
Revision as of 14:14, 5 March 2020 by JoeStrout (talk | contribs) (Created page with "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 s...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
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.

Example

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