Skip to content

Instantly share code, notes, and snippets.

@DavidLari
Last active July 30, 2018 17:08
Show Gist options
  • Save DavidLari/840311c593e1039485660fdf2742c7e8 to your computer and use it in GitHub Desktop.
Save DavidLari/840311c593e1039485660fdf2742c7e8 to your computer and use it in GitHub Desktop.
A simple joystick view written in swift 4.x. Works like classic Atari joystick. Supports InterfaceBuilder.
/*
JoystickView.swift
Created by David Lari on 7/14/18.
MIT License
Copyright © 2018 David Lari.
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
A simple Joystick pad (Atari style), no sprite kit required.
Use: In IB, create a UIView, set its class to JoystickView. Or instantiate in code with a frame.
Then set color properties if desired.
NOTE: Make sure to set a completionHandler to get results. You will get x,y Int results. Values for x and y will be -1, 0 or 1 corresponding to the 8 directions.
x,y for each direction:
| |
-1,-1 | 0,-1 | 1,-1
______|______|______
| |
-1,0 | | 1,0
______|______|______
| |
-1,1 | 0,1 | 1,1
| |
*/
import UIKit
@IBDesignable
public class JoystickView: UIView {
//MARK: - Public Properties
// backing vars for inspectables
var _borderColor = UIColor.lightGray
var _buttonBackgroundColor = UIColor.darkGray
var _buttonForegroundColor = UIColor.white
var _speedInMilliseconds = 100
@IBInspectable
public var borderColor: UIColor {
get {
return _borderColor
} set {
_borderColor = newValue
setButtonBorders()
setNeedsDisplay()
}
}
@IBInspectable
public var buttonBackgroundColor: UIColor {
get {
return _buttonBackgroundColor
} set {
_buttonBackgroundColor = newValue
setButtonBackgroundColors()
setNeedsDisplay()
}
}
@IBInspectable
public var buttonForegroundColor: UIColor {
get {
return _buttonForegroundColor
} set {
_buttonForegroundColor = newValue
for button in buttonArray {
button.setTitleColor(newValue, for: .normal)
setNeedsDisplay()
}
}
}
/// Repeat speed, in milliseconds for when buttons are held down. Values below 1 are set to 1 to prevent disruption of the time space continuum. ;)
@IBInspectable
public var speedInMilliseconds: Int {
get {
return _speedInMilliseconds
} set {
_speedInMilliseconds = max(newValue, 1)
speedInSeconds = Double( _speedInMilliseconds) / 1000.0
}
}
public var completionHandler: ((Int, Int) -> Void)?
//MARK: - Private constants
private let upLeftButton = UIButton()
private let upButton = UIButton()
private let upRightButton = UIButton()
private let leftButton = UIButton()
private let rightButton = UIButton()
private let downLeftButton = UIButton()
private let downButton = UIButton()
private let downRightButton = UIButton()
//MARK: - Private variables
private var buttonArray: [UIButton]!
private var isButtonTouched = false
private var speedInSeconds = 0.1 // repeat speed, computed from _speedInMilliseconds
override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
override public func prepareForInterfaceBuilder() {
super.prepareForInterfaceBuilder()
setup()
}
private func setup() {
_borderColor = UIColor.lightGray
_buttonBackgroundColor = UIColor.darkGray
_buttonForegroundColor = UIColor.white
_speedInMilliseconds = 100
buttonArray = [upLeftButton, upButton, upRightButton, leftButton, rightButton, downLeftButton, downButton, downRightButton]
backgroundColor = .clear
let width = frame.width / 3
let height = frame.height / 3
upLeftButton.frame = CGRect(x: 0, y: 0, width: width, height: height)
upButton.frame = CGRect(x: width, y: 0, width: width, height: height)
upRightButton.frame = CGRect(x: 2 * width , y: 0, width: width, height: height)
leftButton.frame = CGRect(x: 0, y: height, width: width, height: height)
rightButton.frame = CGRect(x: 2 * width, y: height, width: width, height: height)
downLeftButton.frame = CGRect(x: 0, y: 2 * height, width: width, height: height)
downButton.frame = CGRect(x: width, y: 2 * height, width: width, height: height)
downRightButton.frame = CGRect(x: 2 * width, y: 2 * height, width: width, height: height)
for button in buttonArray {
button.addTarget(self, action: #selector(buttonReleased), for: .touchUpInside)
button.addTarget(self, action: #selector(buttonTouchDown), for: .touchDown)
button.setTitleColor(buttonForegroundColor, for: .normal)
addSubview(button)
}
setButtonBorders()
upButton.setTitle("\u{2191}", for: .normal)
leftButton.setTitle("\u{2190}", for: .normal)
rightButton.setTitle("\u{2192}", for: .normal)
downButton.setTitle("\u{2193}", for: .normal)
upLeftButton.setTitle("\u{2196}", for: .normal)
upRightButton.setTitle("\u{2197}", for: .normal)
downLeftButton.setTitle("\u{2199}", for: .normal)
downRightButton.setTitle("\u{2198}", for: .normal)
setButtonBackgroundColors()
}
private func setButtonBorders() {
for button in [upButton, leftButton, downButton, rightButton] {
button.layer.borderWidth = 1
button.layer.borderColor = _borderColor.cgColor
}
roundedButton(button: upLeftButton, corner: .topLeft)
roundedButton(button: upRightButton, corner: .topRight)
roundedButton(button: downLeftButton, corner: .bottomLeft)
roundedButton(button: downRightButton, corner: .bottomRight)
}
private func setButtonBackgroundColors() {
for button in [upButton, downButton, leftButton, rightButton] {
button.backgroundColor = buttonBackgroundColor
}
roundedButton(button: upLeftButton, corner: .topLeft)
roundedButton(button: upRightButton, corner: .topRight)
roundedButton(button: downLeftButton, corner: .bottomLeft)
roundedButton(button: downRightButton, corner: .bottomRight)
}
private func roundedButton(button: UIButton, corner: UIRectCorner){
// Due to limitations of byRoundingCorners, numbers are clamped to 1/2 of size by Apple. :(
let diameter = button.frame.width
let maskPath = UIBezierPath(roundedRect: button.bounds,
byRoundingCorners: corner,
cornerRadii: CGSize(width: diameter, height: diameter))
let maskLayer = CAShapeLayer()
maskLayer.path = maskPath.cgPath
maskLayer.lineWidth = 1
maskLayer.strokeColor = _borderColor.cgColor
maskLayer.fillColor = buttonBackgroundColor.cgColor
maskLayer.frame = button.bounds
button.layer.addSublayer(maskLayer)
}
@objc func buttonTouchDown(sender: UIButton!) {
if !isButtonTouched {
isButtonTouched = true
self.move(sender: sender)
}
}
@objc func buttonReleased(sender: UIButton!) {
isButtonTouched = false
}
private func move(sender: UIButton!) {
guard isButtonTouched else { return }
var x = 0
var y = 0
switch sender {
case upLeftButton, leftButton, downLeftButton:
x = -1
case upRightButton, rightButton, downRightButton:
x = 1
default:
break
}
switch sender {
case upLeftButton, upButton, upRightButton:
y = -1
case downLeftButton, downButton, downRightButton:
y = 1
default:
break
}
completionHandler?(x, y)
delay(speedInSeconds) {
self.move(sender: sender)
}
}
private func delay(_ delay: Double, closure: @escaping () -> Void) {
DispatchQueue.main.asyncAfter(
deadline: DispatchTime.now() + Double(Int64(delay * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC), execute: closure)
}
}
@DavidLari
Copy link
Author

It's not quite pixel perfect on the borders. I'm working on that.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment