Skip to content

Instantly share code, notes, and snippets.

@paul-reilly
Created November 27, 2017 11:21
Show Gist options
  • Save paul-reilly/8773861833b498a5cc6b3084f97d5e38 to your computer and use it in GitHub Desktop.
Save paul-reilly/8773861833b498a5cc6b3084f97d5e38 to your computer and use it in GitHub Desktop.
-- VirtualRelativeJoystick for Gideros
--
-- Onscreen joystick that only appears when lower left quadrant
-- of screen is touched
--
VirtualRelativeJoystick = Core.class(Sprite)
function VirtualRelativeJoystick:init(options)
self.x = options.x or 100
self.y = options.y or 100
self.outerRadius = options.outerRadius or 100
self.outerCircle = self:getNewCircle(self.outerRadius, false)
self:addChild(self.outerCircle)
self.innerNubbin = self:getNewCircle(self.outerRadius * .5, true)
self:addChild(self.innerNubbin)
self:setPosition(self.x, self.y)
self:setVisible(false)
self:addEventListener(Event.TOUCHES_BEGIN, self.onTouchesBegin, self)
self.xpos, self.ypos, self.strength, self.angle = 0, 0, 0, 0
end
--
function VirtualRelativeJoystick:onTouchesCancel(e)
self:onTouchesEnd(e)
end
--
function VirtualRelativeJoystick:onTouchesBegin(e)
if e.touch.x > application:getContentWidth() * .5 or
e.touch.y < application:getContentHeight() * .5 then return end
self:addEventListener(Event.TOUCHES_MOVE, self.onTouchesMove, self)
self:addEventListener(Event.TOUCHES_END, self.onTouchesEnd, self)
self.controlTouchId = e.touch.id
self:setPosition(e.touch.x, e.touch.y)
self:setVisible(true)
e:stopPropagation()
end
--
function VirtualRelativeJoystick:onTouchesMove(e)
if e.touch.id == self.controlTouchId then
local x, y = self:globalToLocal(e.touch.x, e.touch.y)
local radius = self.outerRadius
local distance = math.sqrt(x * x + y * y)
-- normalized strength for use with angle
self.strength = (distance >< radius) / radius
self.angle = ^>math.atan2(y, x) + 90.
x = (x <> -radius) >< radius
y = (y <> -radius) >< radius
self.xpos, self.ypos = x / self.outerRadius, -y / self.outerRadius
self.innerNubbin:setPosition(x, y)
e:stopPropagation()
end
end
--
function VirtualRelativeJoystick:onTouchesEnd(e)
if e.touch.id == self.controlTouchId then
self:removeEventListener(Event.TOUCHES_MOVE, self.onTouchesMove, self)
self:removeEventListener(Event.TOUCHES_END, self.onTouchesEnd, self)
self.innerNubbin:setPosition(0, 0)
self.xpos, self.ypos = 0, 0
self:setVisible(false)
e:stopPropagation()
end
self.controlTouchId = nil
end
--
function VirtualRelativeJoystick:getNewCircle(radius, filled)
local p = Path2D.new()
r = radius
p:setSvgPath(("M %s 0 a %s %s 0 0 0 %s 0 a %s %s 0 0 0 %s 0 Z"):format(-r, r, r, 2*r, r, r, -2*r))
p:setLineThickness(10) -- Outline width
p:setFillColor(0xdddddd, filled and .6 or .0) --Fill color
p:setLineColor(0xdddddd, .6) --Line color
return p
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment