So I haven’t really posted anything I’ve created on the forum yet, so I thought I should already. This is an analog stick class that I made for use in various games since it’s become a common control device in mobile games. Feel free to edit/optimize it or change the styling to fit your needs.
AnalogStick = class()
function AnalogStick:init(x, y)
self.center = vec2(x, y)
self.backboardSize = 150
self.backboardRadius = self.backboardSize/2
self.capSize = 80
self.grabbed = false
self.capPos = vec2(self.center.x, self.center.y)
self.dragDist = 0
end
function AnalogStick:draw()
pushStyle()
fill(210, 208, 208, 255)
stroke(164, 158, 158, 255)
ellipse(self.center.x, self.center.y, self.backboardSize)
fill(159, 150, 150, 255)
stroke(121, 119, 119, 255)
ellipse(self.capPos.x, self.capPos.y, self.capSize)
popStyle()
end
function AnalogStick:touched(touch)
self.dragDist = self.center:dist(vec2(touch.x, touch.y))
if touch.state ~= ENDED and self.dragDist <= self.backboardRadius then
self.capPos = vec2(touch.x, touch.y)
self.grabbed = true
return {mag = self.dragDist/self.backboardRadius, angle = math.deg(math.atan(self.capPos.x-self.center.x, self.capPos.y-self.center.y))}
elseif touch.state == MOVING and self.grabbed == true and self.dragDist > self.backboardRadius then
-- VVV Learn about this more VVV
k = self.backboardRadius/self.center:dist(vec2(touch.x, touch.y))
self.capPos = self.center+k*(vec2(touch.x, touch.y)-self.center)
self.grabbed = true
return {mag = 1, angle = math.deg(math.atan(self.capPos.x-self.center.x, self.capPos.y-self.center.y))}
else
self.capPos = vec2(self.center.x, self.center.y)
self.grabbed = false
self.dragDist = 0
return {mag = 0, angle = 0}
end
end