to re-use, optimize, comment, ...,enjoy
Code: Select all
REM Joystick
REM sB 5.3 / iPhone4 / iOS 6.1 / by Operator
REM
REM joystick initialization js_ini()
REM joystick js() availabe values:
REM js.dmax: max distance of stick
REM js.amp: amplitude of stick: 0..1
REM js.DX: distance x of stick from js-center
REM js.Dy: distance y of stick from js-center
REM js.angle: angle of stick: -pi..pi
'test the joystick
'move something around (a circle as sprite)
'create circle sprite
OPTION SPRITE POS CENTRAL
GRAPHICS
REFRESH OFF
GRAPHICS CLEAR
scw = SCREEN_WIDTH()
sch = SCREEN_HEIGHT()
FILL COLOR 0,0,1
cir_x = 150
cir_y = 150
cir_r = 15
cir_speed_cal = 0.05
FILL CIRCLE cir_x,cir_y SIZE cir_r
SPRITE "cir" SCAN (cir_x-cir_r)-2, (cir_y-cir_r)-2, 2*cir_r+4, 2*cir_r+4
SPRITE "cir" AT 150,150
SPRITE "cir" SHOW
js_ini() 'initialize the joystick
GRAPHICS CLEAR 0,0,0
REFRESH ON
LOOP:
js() 'update joystick positions
cir_speed = js.AMPLI*cir_speed_cal
cir_dx = js.DX*cir_speed
cir_dy = js.DY*cir_speed
cir_x = cir_x + cir_dx
cir_y = cir_y + cir_dy
SPRITE "cir" AT cir_x,cir_y
FIELD "debug" TEXT "Speed: "&INT(100*cir_speed)&" Angle: "&INT(180*js.ANGLE/3.14156)
GOTO LOOP
DEF js_ini()
'joystick initialize
'recenter, resize if req
cx = 70 'joystick centre-x
cy = 370 'joystick centre-y
icr = 30 'joystick inner circle radius
ocr = 50 'joystick outer circle radius
sc = 1.2 'joystick scale
dxy_max = (ocr-icr)*sc
'draw joystick and save it as a sprite
'joystick made out of outer and inner circle
'joystick outer circle
FILL COLOR 1,1,1
FILL ALPHA 0.2
FILL CIRCLE cx,cy SIZE sc*ocr
SPRITE "js_oc" SCAN cx-(sc*ocr)-1,cy-(sc*ocr)-1, (sc*2*ocr)+2,(sc*2*ocr)+2
GRAPHICS CLEAR
'inner circle
FILL COLOR 1,1,1
FILL ALPHA 0.2
FILL CIRCLE cx,cy SIZE sc*icr
SPRITE "js_ic" SCAN cx-(sc*icr)-1,cy-(sc*icr)-1, sc*(2*icr)+2,sc*(2*icr)+2
GRAPHICS CLEAR
'show joystick
OPTION SPRITE POS CENTRAL
SPRITE "js_oc" AT cx,cy
SPRITE "js_ic" AT cx,cy
SPRITE "js_ic" SHOW
SPRITE "js_oc" SHOW
FIELD "debug" TEXT "" AT 0,0 SIZE 200,40 RO
FIELD "debug" BACK COLOR 0,0,0
FIELD "debug" FONT COLOR 1,1,2
FIELD "debug" BACK ALPHA 0
END DEF
DEF js()
dxy_max = js_ini.dxy_max 'max travel of joys.
ANGLE = 0
GET TOUCH 0 AS tx,ty
IF SPRITE_HIT ("js_oc", tx,ty) THEN
DX = tx - js_ini.cx
DY = ty - js_ini.cy
DXY = SQR(DX^2 + DY^2)
IF DXY > dxy_max THEN DXY = dxy_max
AMPLI = DXY/dxy_max
ANGLE = ATAN2(DY,DX)
last_ANGLE = ANGLE
js_ic_x = DXY*COS(ANGLE) + js_ini.cx
js_ic_y = DXY*SIN(ANGLE) + js_ini.cy
SPRITE "js_ic" AT js_ic_x, js_ic_y
END IF
'return joystick to the center
IF tx = -1 AND DXY > 0 THEN
DXY = DXY - 1
IF DXY < 0.1 THEN
DXY = 0
DX = 0
DY =0
AMPLI = DXY/dxy_max
END IF
js_ic_x = DXY*COS(last_ANGLE) + js_ini.cx
js_ic_y = DXY*SIN(last_ANGLE) + js_ini.cy
SPRITE "js_ic" AT js_ic_x, js_ic_y
END IF
END DEF