Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Analog Stick

edited February 2016 in Code Sharing Posts: 22

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) = vec2(x, y)
    self.backboardSize = 150
    self.backboardRadius = self.backboardSize/2
    self.capSize = 80
    self.grabbed = false
    self.capPos = vec2(,
    self.dragDist = 0

function AnalogStick:draw()

    fill(210, 208, 208, 255)
    stroke(164, 158, 158, 255)

    ellipse(,, self.backboardSize)

    fill(159, 150, 150, 255)
    stroke(121, 119, 119, 255)

    ellipse(self.capPos.x, self.capPos.y, self.capSize)


function AnalogStick:touched(touch)
    self.dragDist =, 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(,}

    elseif touch.state == MOVING and self.grabbed == true and self.dragDist > self.backboardRadius then
        -- VVV Learn about this more VVV
        k = self.backboardRadius/, touch.y))
        self.capPos =*(vec2(touch.x, touch.y)
        self.grabbed = true

        return {mag = 1, angle = math.deg(math.atan(,}

        self.capPos = vec2(,
        self.grabbed = false
        self.dragDist = 0

        return {mag = 0, angle = 0}


  • dave1707dave1707 Mod
    Posts: 10,053

    @captsmitty77 When you post code, put 3 ~'s on a line before and after the code so it shows properly.

  • Ok, thanks @dave1707

  • IgnatzIgnatz Mod
    edited February 2016 Posts: 5,396

    @captsmitty77 - thanks for sharing.

    you are more like to get people trying your code if you can provide a simple example using it, so they can see how it works. A little video sometimes helps too.

    Also, you might find the angleBetween function useful, which can be used to get the angle between two vec2's.

  • Thanks for the advice @Ignatz. I'll check out angleBetween also

Sign In or Register to comment.