Greencat
Greencat

Reputation: 142

Preventing SKSpriteNode from going off screen

I have a SKSpriteNode that moves with the accelerometer by using the following code:

-(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)];

    }
}

This works well however, the node (gamefish) moves off the screen. How can I prevent this and have it stay on the screen?

Upvotes: 0

Views: 583

Answers (2)

Patrick Collins
Patrick Collins

Reputation: 4334

Try using an SKConstraint which was designed exactly for this purpose and introduced in iOS8:

Just add this to the setup method of the gameFish node. The game engine will apply the constraint after the physics has run. You won't have to worry about it. Cool huh?

// 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

Upvotes: 2

sangony
sangony

Reputation: 11696

The code depends on whether you have added the gameFish node to self or to another node (something like a "worldNode"). If you have added it to self, look at the code below:

// 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);
}

For the bottom you can do a check of < 0 or whatever value you need.

Upvotes: 0

Related Questions