我在stackoverflow中找到了this巧妙的解决方案。不幸的是,这段代码在我的项目中不起作用。我尝试在四个不同的触摸区域划分圆形SKSpriteNode。我还想改变区域的颜色(仅当按下区域时)。你知道怎么做吗?
举个例子或帮助我非常感激。
我的代码:
- (void)setUpDPad {
_dPad = [SKSpriteNode spriteNodeWithImageNamed:@"dpad"];
_dPad.anchorPoint = CGPointMake(0.0, 0.0);
_dPad.position = CGPointMake(0.0-self.frame.size.width/2+5, 0.0-self.frame.size.height/2+50);
_dPad.zPosition = 1;
[self addChild:_dPad];
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
for (UITouch *touch in touches) {
CGPoint location = [touch locationInNode:self];
CGFloat angle = [self angleToPoint:location];
int area = [self sectionForAngle:angle];
if ([_dPad containsPoint:location]) {
if (area == 1) {
}
if (area == 2) {
}
if (area == 3) {
}
if (area == 4) {
}
}
}
}
- (float)angleToPoint:(CGPoint)tapPoint {
int x = _dPad.frame.size.width/2;
int y = _dPad.frame.size.height/2;
float dx = tapPoint.x - x;
float dy = tapPoint.y - y;
CGFloat radians = atan2(dy,dx);
CGFloat degrees = radians * 180 / M_PI;
if (degrees < 0) return fabs(degrees);
else return 360 - degrees;
}
- (int)sectionForAngle:(float)angle {
if (angle >= 45 && angle < 135) {
return 1;
}
else if (angle >= 135 && angle < 225) {
return 2;
}
else if (angle >= 225 && angle < 315) {
return 3;
}
else {
return 4;
}
}