Teja Nandamuri
Teja Nandamuri

Reputation: 11201

Adding SKPhysicsBody causes the SKSpriteNode to shake

I have two SkSpriteNodes called left-ball and right-ball.THey flow from sides of the screen.

I implemented the collision detection for these two balls. However I noticed that before I add collision detection, the balls were moving smoothly without any shaking effect, but after I add the collision detection, the balls were shaking and moving in their path.

I am using the same bit category for both of these balls:

   static const int ballHitCategory = 1;

without shaking:

enter image description here

with shaking:

enter image description here

Here is what I tried in code:

_leftBall.physicsBody=[SKPhysicsBody bodyWithRectangleOfSize:_leftBall.frame.size];
_leftBall.physicsBody.categoryBitMask=ballHitCategory;
_leftBall.physicsBody.contactTestBitMask=ballHitCategory;
_leftBall.physicsBody.collisionBitMask=ballHitCategory;
_leftBall.physicsBody.dynamic=YES;
_leftBall.physicsBody.usesPreciseCollisionDetection=YES;

 _rightBall.physicsBody=[SKPhysicsBody bodyWithRectangleOfSize:_rightBall.frame.size];
_rightBall.physicsBody.categoryBitMask=ballHitCategory;
_rightBall.physicsBody.contactTestBitMask=ballHitCategory;
_rightBall.physicsBody.collisionBitMask=ballHitCategory;
_rightBall.physicsBody.dynamic=YES;
_rightBall.physicsBody.usesPreciseCollisionDetection=YES;




-(void)didBeginContact:(SKPhysicsContact *)contact
{

    _leftBall = (SKSpriteNode*)contact.bodyA.node;
    _rightBall = (SKSpriteNode *)contact.bodyB.node;

    if(_leftBall.physicsBody .categoryBitMask == ballHitCategory ||  _rightBall.physicsBody.categoryBitMask == ballHitCategory)
    {

        NSLog(@" hit the ");
        //setup your methods and other things here
        [_leftBall removeFromParent];
        [_rightBall removeFromParent];


    }
}

Please note that shake happens only after I add the collision detection, If I remove the above code, everything is fine.

What is the proper way to add collision detection without effecting the skspritenode ?

Upvotes: 3

Views: 374

Answers (2)

Ben
Ben

Reputation: 984

Don't worry about the Gravity. You should set your spritenode:

_leftBall.physicsBody.dynamic=YES;
_leftBall.physicsBody.affectedByGravity=NO;

Same on _rightBall

Upvotes: 0

hamobi
hamobi

Reputation: 8130

so youre moving the sprites using non physics code.. but theyre still part of the physics simulation. I'm guessing theyre fighting against the force of gravity.

either set affectedByGravity on each sprite to false

or you can turn off gravity in your game completely

[self.physicsWorld setGravity:CGVectorMake(0, 0)];

Upvotes: 2

Related Questions