Search code examples
cocos2d-xchipmunk

Wierd behaviour with cc.PhysicsSprite in cocos2dx and chipmunk


I have a game where balls bounce around the screen - simple. I have walls that prevent balls from escaping the screen space. I use the following code to add balls to the screen, which happens with some delay between each addition:

        var ball = {};
        ball.markedForDelete = false;
        ball.dir = spawnPoint.dir;

        var ballMass = 1;
        var ballBody = new cp.Body( ballMass, cp.momentForCircle( ballMass, 0, this._ballRadius, cp.v(0,0) ) );
        ballBody.setPos( spawnPoint.position );

        var magnitude = 200;
        var ang = spawnPoint.dir * Math.PI / 180;
        var vel = cp.v( magnitude * Math.cos(ang), magnitude * Math.sin(ang) );

        var shape = new cp.CircleShape( ballBody, this._ballRadius, cp.v( 0,0 ) );
        shape.ballShapeId = this.model.getNextBallShapeId ();
        shape.setElasticity( 1 );
        shape.setFriction( 0 );
        shape.setCollisionType( collision_type );
        this._space.addShape( shape );
        ball.shape = shape;
        shape.ball = ball;

        var sprite = cc.PhysicsSprite.create( file );
        sprite.nodeName = "Ball:" + shape.ballShapeId;
        sprite.setColor( cc.c3b( 255, 255, 255 ) );
        sprite.setScale ( 0.5 * this.ballScale );
        sprite.setBody( ballBody );
        this._gameStage.addChild( sprite, 5 );
        ball.sprite = sprite;
        sprite.ball = ball;

        this._space.addBody( ballBody );
        ballBody.setVel( vel )  ;

        return ball;

This code works as expected when running on a device (iOS or Android), but when I use exact same code on the web things get weird. First, it spawns about 4 balls from random spawn points without a hitch, but all following balls get spawned on top of an existing ball and seems like the two (or three or four depending on how long you play) share physics. If I enable debug physics node: cc.PhysicsDebugNode.create( this._space ); I can see that these balls are right over each other and they stack velocities. What is going on? Is there a limit on how many I can have? Any pointers? I am so lost and confused.

Thanks!


Solution

  • So, i figured it out. I created an array of 4 spawn points (notice it matches how many balls i was seeing). Each spawn point was something like this spawnPoint: { position: cc.p ( x, y ) }. So, when I assign position for the body using ballBody.setPos( spawnPoint.position ) it was not creating a new cc.p object to store position, but actually using the one i provided. So, every ball i created shared one of these 4 positions. On mobile devices this works properly and cc.p is actually created, instead of just pointing to the one I provided. Hope it helps someone.