【发布时间】:2015-10-07 14:21:22
【问题描述】:
在掌握 iOS 和 SpriteKit 时,我正在使用 Objective-C 开发游戏。它基本上是一个自上而下的驾驶游戏,带有一个速度按钮和两个左右方向按钮。 但是我似乎无法弄清楚如何正确地使转向工作。
到目前为止,我已经实现了三个按钮,它们可以使节点(汽车)向前移动,并以一定角度转动。相关代码如下所示:
#define SK_DEGREES_TO_RADIANS(__ANGLE__) ((__ANGLE__) * 0.01745329252f)
#define SK_RADIANS_TO_DEGREES(__ANGLE__) ((__ANGLE__) * 57.29577951f)
@implementation GameScene {
SKSpriteNode *car;
int speed;
int rotation;
BOOL turnRight;
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [touches anyObject];
CGPoint location = [touch locationInNode:self];
SKNode *node = [self nodeAtPoint:location];
// Drive button
if ([node.name isEqualToString:@"driveNode"]) {
speed = 120;
}
// Right
if ([node.name isEqualToString:@"moveRight"]) {
turnRight = YES;
rotation = rotation + 20;
}
// Left
if ([node.name isEqualToString:@"moveLeft"]) {
rotation = rotation - 20;
}
}
对于更新:
-(void)update:(CFTimeInterval)currentTime {
if (turnRight == YES) {
NSLog(@"Turning right..");
/*
I imagine that calculations should be done here
*/
}
float angle = atan2f(speed, rotation);
car.zRotation = angle - SK_DEGREES_TO_RADIANS(90);
CGFloat rate = 1;
CGVector relativeVelocity = CGVectorMake(rotation, speed - car.physicsBody.velocity.dy);
car.physicsBody.velocity = CGVectorMake(rotation, car.physicsBody.velocity.dy + relativeVelocity.dy * rate);
}
我在touchesEnded中将turnRight的值设置为NO
我的问题是,按照现在的实施方式,汽车不能向右转多于水平转。我想要的是当继续按下右键时,汽车最终应该以恒定速度行驶一圈。我无法弄清楚如何实现这一点的逻辑和数学。
我检查了this question 等,这在某种程度上帮助了我,但我还没有完全弄清楚。
任何人都可以在这里把我引向正确的方向吗?我浏览了网络和堆栈以寻找解决方案,但没有找到任何可以帮助我的方法。
【问题讨论】:
-
那些看起来像全局变量?
-
是的,我已经在@implementation 下实现了它们
-
它们听起来仍然像全局变量,除非它们在初始声明部分(即
{和})。 -
我已经更新了上面的代码,你是这个意思吗?
-
是的;现在它们是正确的(私有)实例变量。
标签: ios objective-c sprite-kit skspritenode