making an image face the mouse
Blitz3D Forums/Blitz3D Beginners Area/making an image face the mouse
| ||
in my game i have a little guy with a gun, it's a 2d overview. i want to know how i can have him always facing the crosshairs (my mouse) no matter where he is when i move the mouse around freely on the screen |
| ||
You should have an image for each direction that the guy looks at. Say, you are using 9 images, up-left up up-right left middle right down-left down-middle and down-right. You can line them up into a big image and load them with LoadAnimImage. Suppose you have the Graphics mode set to 800x600, you can use this: fr = (MouseX() / 266) + (MouseY() / 200) * 3 DrawImage image, 400, 300, fr "fr" is the index number of the frame that should be drawn. The 800x600 screen is divided in 9 parts, 3 over the x-axis and 3 over the y-axis: 800/3=266 and 600/3=200. |
| ||
EDIT: use ATan2() instead, it does all of this for you. To get the angle from one point to another, subtract and use arctan: Local dir# Local dx# = p\x - MouseX() Local dy# = p\y - MouseY() If dy < 0 Then dir = ATan(dx/dy) If dy > 0 Then dir = ATan(dx/dy) + 180 If dy = 0 Then ; don't divide by 0! If dx < 0 Then dir = 90 Else dir = 270 EndIf I snagged this from some of my code in an old discussion about Plobb. There may be a more elegant approach. |
| ||
Here .. set no of possible image directions by changing Segs .. You could probably simplify the imageNo calc but I can't really think atm. Hope it helps. Graphics 640,480,16,1 Global ImageNo Global PlayerX# = 320 Global PlayerY# = 240 Global Segs = 16 SetBuffer BackBuffer() While Not KeyDown(1) Cls ;show angle range Color 128,128,128 For l = 0 To Segs-1 A# = ( Float(l) + .5 ) * ( 360.0 / Float( Segs ) ) Line 320 , 240 , 320 + 100 * Cos( A ) , 240 + 100 * Sin( A ) Next ;get angle from player to cursor Dx# = MouseX() - PlayerX Dy# = MouseY() - PlayerY If Sqr( Dx * Dx + Dy * Dy ) > 5.0 Angle# = ATan2 ( Dy , Dx ) ImageNo = Floor( ( ( Angle + 360 ) Mod 360 + ( 180 / Segs ) ) / ( 360 / Segs ) ) Mod Segs EndIf Color 255,255,0 Text 0,0,"Angle : "+Angle Text 0,10,"Image No : "+ImageNo ;draw player Color 255,0,0 Oval PlayerX - 5, PlayerY - 5 , 11, 11 ;draw cursor Color 255,255,255 Line MouseX() - 5 , MouseY(), MouseX() +5, MouseY() Line MouseX(), MouseY()-5, MouseX(), MouseY()+5 Flip Wend |