Difference between revisions of "How to move a sprite forward"

From MiniScript Wiki
Jump to navigation Jump to search
(Created page with "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...")
 
m
 
(One intermediate revision by one other user not shown)
Line 1: Line 1:
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.
+
Move a [[Sprite|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.
 +
 
 +
If "forward" for your sprite is not oriented to the right in the unrotated sprite image, then simply add some constant (e.g. 90) to the sprite rotation before converting to degrees.  The same can be done to make a sprite move left or right relative to whatever way it is facing.  To move backwards, you could either add 180 degrees, or simply use a negative speed.
  
 
== Example ==
 
== Example ==

Latest revision as of 20:01, 20 November 2021

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.

If "forward" for your sprite is not oriented to the right in the unrotated sprite image, then simply add some constant (e.g. 90) to the sprite rotation before converting to degrees. The same can be done to make a sprite move left or right relative to whatever way it is facing. To move backwards, you could either add 180 degrees, or simply use a negative speed.

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