1
votes

I'm making a game with SpriteKit that involves a hero bouncing on a surface in the positive x and y direction. The hero has this size:

CGSize heroSize = CGSizeMake(hero.size.width-140, hero.size.height-35);
hero.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:heroSize];
hero.physicsBody.usesPreciseCollisionDetection = YES;

and uses applyImpulse to bounce in the positive x/y direction:

[self.physicsBody applyImpulse:CGVectorMake(xvelocity, yvelocity)];
SKAction *rotation = [SKAction rotateByAngle: -2.0/M_PI duration:.5];
[self runAction: rotation];

The ground has a friction level of 0.4 and restitution of .5. Because the hero rotates when bouncing, he will sometimes bounce backwards and have a negative X velocity. I was wondering if there is any way to prevent an SKSpriteNode from moving in the -X direction. Would a solution be to create a better size for the physics body of my SKSpriteNode? It seems like this could happen with any shape, but would be less likely with more circular objects. Any input is greatly appreciated.

Thanks

1
How about adding the hero to another node and apply the impuls to that node instead? - Akaino
I thought of a workaround that I could use help with. I want to prevent the hero from moving past the left side of the visible screen. I want there to be an invisible wall on the left side of the screen that prevents the hero from moving past it if it starts to move in the - X direction. Right now, I have the camera centering itself on the hero on the didSimulatePhysics method. So, if the hero moves with negative X velocity then I stop centering the camera on the hero and create an invisible wall that is -self.view.frame.size.width/2 away from the hero. Does this sound good? - JoshNussbaum
If it is -self.view.frame.size.width/2 from the hero, it might be out of screen if the hero is not properly centered. - Akaino

1 Answers

1
votes

You can monitor your hero's velocity and limit negative x movement by using this:

if(hero.physicsBody.velocity.dx < 0) {
    hero.physicsBody.velocity = CGVectorMake(0, hero.physicsBody.velocity.dy);
}