Rotate Sprite To Point (turn sprite towards a point)

Started by kevin, May 17, 2009, 09:03:29 PM

Previous topic - Next topic

kevin

 RotateSpriteToPoint

 This example includes a function to rotate/turn a sprite towards a target point.  


PlayBASIC Code: [Select]
// Create image so we've something to look at
Shape=NewConvexShape(20,3)
DrawShape Shape,20,20,2
GetImage 1,0,0,40,40
PrepareFxImage 1


// create sprite with this image
Spr=NewSprite(400,300,1)
spritedrawmode spr,2
centerspritehandle spr

// limit the umber of syncs per second
Setfps 60

// main loop of demo
Do
Cls 0

// get mouse pointer
mx=mousex()
my=mousey()


// Call function to rotate a sprite towards the mouse pointer
RotateSpriteToPoint(Spr,mx,my,5)

// get the sprites angle and position
angle# =getspriteangle(spr)
x1# =getspritex(spr)
y1# =getspritey(spr)

// project a line from this sprite axis in the direction it's facing
x2#=x1#+cosradius(angle#,50)
y2#=y1#+sinradius(angle#,50)
line x1#,y1#,x2#,y2#

// display the current angle
centertext x1#,y1#-50,Angle#


// Display target as circle (mouse pointer)
circle mx,my,5,false


// draw all the sprites
DrawALLsprites


// Flip the back buffer to the front so we can see it
Sync

// continue this Do/loop
loop



Function RotateSpriteToPoint(Spr,targetx#,targetY#,speed#)
// position of sprite
x#=GetSpritex(Spr)
y#=GetSpriteY(Spr)
// angle of sprite
angle#=GetSpriteAngle(Spr)

// angle towards target from sprite
TargetAngle#=GetAngle2d(x#,y#,targetx#,targety#)

// see if the target is angle is greater than the speed
diff#=AngleDifference(angle#,targetangle#)
if diff#>Speed#

// Get the turn direction based on the
Direction=turndirection(Angle#,TargetAngle#,speed#)
// get the direction to turn
if Direction<>0
// rotate the sprite according
rotatesprite spr,wrapangle(angle#,speed#*Direction)
endif
endif
EndFunction





reno

More games ? Go to my website :)
http://www.thereeteam.com/