I created two classes that are free-to-use. They demonstrate how to create a joystick and how to point an arrow in the general direction of a sprite.
--# Arrow
Arrow = class()
function Arrow:init()
-- you can accept and set parameters here
end
function Arrow:draw(x,y)
local pos = vec2(x,y)
pushMatrix()
translate(x,y)
rotate(self:angleBetween(spritePos,pos))
sprite("Tyrian Remastered:Arrow Right",0,0,100)
popMatrix()
end
function Arrow:angleBetween(ptA,ptB)
local angle=math.deg(math.atan2(ptA.y-ptB.y,ptA.x-ptB.x))
return angle
end
--# Joystick
Joystick = class()
function Joystick:init(x,y)
self.initial = vec2(x,y)
self.rect = vec2(x,y)
self.circle = vec2(x,y)
self.sensitivity = 10 -- higher the number, lower the sensitivity
end
function Joystick:draw()
self.deltaX,self.deltaY = self.circle.x-self.initial.x,self.circle.y-self.initial.y
spritePos.x = spritePos.x + self.deltaX/self.sensitivity
spritePos.y = spritePos.y + self.deltaY/self.sensitivity
pushStyle()
fill(89, 89, 99, 100)
rectMode(CENTER)
rect(self.rect.x,self.rect.y,200,100)
fill(103, 111, 119, 255)
ellipse(self.circle.x,self.circle.y,50)
popStyle()
end
function Joystick:touched(touch)
t = vec2(touch.x,touch.y)
if t:dist(self.circle)<30 then
self.circle = vec2(t.x,t.y)
end
if self.circle.x>self.rect.x+100 then
self.circle.x=self.rect.x+100
end
if self.circle.x<self.rect.x-100 then
self.circle.x=self.rect.x-100
end
if self.circle.y>self.rect.y+50 then
self.circle.y=self.rect.y+50
end
if self.circle.y<self.rect.y-50 then
self.circle.y=self.rect.y-50
end
if touch.state==ENDED then
self.circle = self.initial
end
end
--# Main
-- Joystick
displayMode(FULLSCREEN)
-- Use this function to perform your initial setup
function setup()
spritePos = vec2(WIDTH/2,HEIGHT/2)
jstick = Joystick(150,150)
arrow = Arrow()
end
function draw()
background(40, 40, 50)
jstick:draw()
if spritePos.x>WIDTH then--or spritePos.x<0 or spritePos.y>HEIGHT or spritePos.y<0 then
arrow:draw(WIDTH-100,HEIGHT/2)
elseif spritePos.x<0 then
arrow:draw(100,HEIGHT/2)
elseif spritePos.y>HEIGHT then
arrow:draw(WIDTH/2,HEIGHT-100)
elseif spritePos.y<0 then
arrow:draw(WIDTH/2,100)
end
sprite("Planet Cute:Character Boy",spritePos.x,spritePos.y)
end
function touched(touch)
jstick:touched(touch)
end