How to move a sprite forward
Jump to navigation
Jump to search
Move a sprite in its "forward" direction (i.e. in the +X direction when the sprite is not rotated) by using the cos and sin functions, as shown below. Note that cos and sin require an angle in radians, while Sprite.rotation is in degrees. Convert from degrees to radians by multiplying by pi/180.
Example
This example moves a sprite in its forward direction, now and then changing to a new random direction. (If the sprite wanders off the screen, just press Control-C to stop the program, and run again.)
This could be combined with How to point a sprite at a target to make the sprite chase a target (such as the mouse).
clear
sp = new Sprite
sp.image = file.loadImage("/sys/pics/arrows/arrow2.png")
sp.x = 300
sp.y = 320
display(4).sprites.push sp
speed = 2 // (pixels per frame)
while true // (press Control-C to exit)
if rnd < 0.01 then sp.rotation = 360*rnd
ang = sp.rotation * pi/180
sp.x = sp.x + cos(ang) * speed
sp.y = sp.y + sin(ang) * speed
yield
end while