防止 SKSpriteNode 离开屏幕

Preventing SKSpriteNode from going off screen

我有一个 SKSpriteNode,它使用以下代码随着加速度计移动:

-(void)processUserMotionForUpdate:(NSTimeInterval)currentTime {
    SKSpriteNode* ship = (SKSpriteNode*)[self childNodeWithName:@"fishderp"];
    CMAccelerometerData* data = self.motionManager.accelerometerData;
    if (fabs(data.acceleration.y) > 0.2) {
        [gameFish.physicsBody applyForce:CGVectorMake(0, data.acceleration.y)];

    }
}

这很有效,但是节点(gamefish)移出了屏幕。我怎样才能防止这种情况发生并让它留在屏幕上?

代码取决于您是将 gameFish 节点添加到自身还是另一个节点(类似于 "worldNode")。如果你已经添加到self,请看下面的代码:

// get the screen height as you are only changing your node's y
float myHeight = self.view.frame.size.height;

// next check your node's y coordinate against the screen y range
// and adjust y if required
if(gameFish.position.y > myHeight) {
    gameFish.position = CGPointMake(gameFish.position.x, myHeight);
}

对于底部,您可以检查 < 0 或您需要的任何值。

尝试使用专门为此目的设计并在 iOS8 中引入的 SKConstraint:

只需将此添加到 gameFish 节点的设置方法中即可。游戏引擎将在物理具有 运行 后应用约束。您不必担心。很酷吧?

// get the screensize
CGSize scr = self.scene.frame.size;

// setup a position constraint
SKConstraint *c = [SKConstraint
                    positionX:[SKRange rangeWithLowerLimit:0 upperLimit:scr.width]
                    Y:[SKRange rangeWithLowerLimit:0 upperLimit:scr.width]];

gameFish.constraints = @[c]; // can take an array of constraints