«`objc
#import
@interface ViewController : UIViewController
@property (nonatomic, strong) IBOutlet UISwitch enableJoystickSwitch;
@property (nonatomic, strong) IBOutlet UIView joystickView;
@end
@implementation ViewController
— (void)viewDidLoad {
[super viewDidLoad];
// Initialize the joystick view
self.joystickView.frame = CGRectMake(0, 0, 100, 100);
self.joystickView.backgroundColor = [UIColor blueColor];
self.joystickView.layer.cornerRadius = 50;
self.joystickView.userInteractionEnabled = NO;
[self.view addSubview:self.joystickView];
// Add a gesture recognizer to the joystick view
UIPanGestureRecognizer panGestureRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handlePanGesture:)];
[self.joystickView addGestureRecognizer:panGestureRecognizer];
// Initialize the enable joystick switch
self.enableJoystickSwitch.on = NO;
[self.enableJoystickSwitch addTarget:self action:@selector(enableJoystick:) forControlEvents:UIControlEventValueChanged];
}
— (void)handlePanGesture:(UIPanGestureRecognizer )gestureRecognizer {
if (self.joystickView.userInteractionEnabled) {
CGPoint translation = [gestureRecognizer translationInView:self.joystickView];
// Limit the joystick movement to a circular area
CGFloat radius = self.joystickView.frame.size.width / 2;
CGFloat distance = sqrt(pow(translation.x, 2) + pow(translation.y, 2));
if (distance > radius) {
CGFloat angle = atan2(translation.y, translation.x);
translation.x = radius cos(angle);
translation.y = radius sin(angle);
}
// Move the joystick view
self.joystickView.center = CGPointMake(self.joystickView.center.x + translation.x, self.joystickView.center.y + translation.y);
// Reset the translation for the next gesture
[gestureRecognizer setTranslation:CGPointZero inView:self.joystickView];
}
}
— (void)enableJoystick:(UISwitch )sender {
self.joystickView.userInteractionEnabled = sender.on;
}
@end
«`