我正在使用 sprite kit 编写游戏,我已经编写了加速度计代码并且它可以运行。但问题是它在点击屏幕边缘时不会停止,有人可以帮我解决这个问题吗? 这是播放器的代码:
-(void)addShip
{
//initalizing spaceship node
ship = [SKSpriteNode spriteNodeWithImageNamed:@"Spaceship"];
[ship setScale:0.5];
ship.zRotation = - M_PI / 2;
//Adding SpriteKit physicsBody for collision detection
ship.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:ship.frame.size];
ship.physicsBody.mass = 0.02;
ship.physicsBody.categoryBitMask = shipCategory;
ship.physicsBody.dynamic = YES;
ship.physicsBody.affectedByGravity = NO;
ship.physicsBody.contactTestBitMask = DonutCategory | PizzaCategory | ChocolateCategory | SoftCategory | AppleCategory | GrapeCategory | OrangeCategory | BananaCategory;
ship.physicsBody.collisionBitMask = 0;
ship.physicsBody.usesPreciseCollisionDetection = YES;
ship.name = @"ship";
ship.position = CGPointMake(260,30);
[self addChild:ship];
motionManager = [[CMMotionManager alloc] init];
if ([motionManager isAccelerometerAvailable] == YES) {
[motionManager startAccelerometerUpdatesToQueue:[[NSOperationQueue alloc] init]
withHandler:^(CMAccelerometerData *data, NSError *error)
{
float destX, destY;
float currentX = ship.position.x;
float currentY = ship.position.y;
BOOL shouldMove = NO;
if(data.acceleration.x < -0.25) { // tilting the device to the right
destX = currentX + (data.acceleration.x * kPlayerSpeed);
destY = currentY;
shouldMove = YES;
} else if (data.acceleration.x > 0.25) { // tilting the device to the left
destX = currentX + (data.acceleration.x * kPlayerSpeed);
destY = currentY;
shouldMove = YES;
}
if(shouldMove) {
SKAction *action = [SKAction moveTo:CGPointMake(destX, destY) duration:1];
[ship runAction:action];
}
}];
}
}
最佳答案
您可以在屏幕上添加边缘,这样当飞船撞到边缘时物理就会停止(在 init 方法中执行):
self.physicsBody = [SKPhysicsBody bodyWithEdgeLoopFromRect:self.frame];
//Add this to change some behaviour when ship will collide with the screen
//self.physicsBody.friction = 0.0f;
另一种方法是在船舶接触屏幕边缘并改变船舶位置时检查更新方法。
//扩展
我相信 moveTo:duration: 方法会弄乱你的相位,要修复它,只需确保你的 destX 和 destX 大于屏幕尺寸宽度(高度)- 船舶尺寸宽度(高度)并且小于原点 x 和原点 y .
您不应该使用 moveTo:duration: 方法,而应该对您的飞船施加力。 试试这个代码,它和你的有点不同,但这是移动你的船的更好方法(忽略上面的代码):
//Your ship setting
_ship.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:_ship.frame.size];
_ship.physicsBody.mass = 0.02;
_ship.physicsBody.categoryBitMask = shipCategory;
_ship.physicsBody.dynamic = YES;
_ship.physicsBody.affectedByGravity = NO;
// Edge around the screen
self.physicsBody = [SKPhysicsBody bodyWithEdgeLoopFromRect:self.frame];
//Apply movement (instead of moveTo:duration:)
//Get the accelerometer value
CMAccelerometerData* accelData = _motionManager.accelerometerData;
if (fabs(accelData.acceleration.x) > 0.2) {
// 35 is the value you can play with to make your ship movement feel more natural
[_ship.physicsBody applyForce:CGVectorMake(0.0, 35.0 * data.acceleration.x)];
}
关于c++ - Sprite Kit - 玩家使用加速度计移动屏幕,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21332888/