Jump to content

Having trouble with P2 Physics Restitution


Ninjadoodle
 Share

Recommended Posts

Hi guys

I'm trying to learn how to do a bounce in P2 physics.

I have it working with bodies, that are setup specifically in the scenes init() function.

I'm however having trouble, when I want to create a ball 'class' and then spawn the balls on a click, while having them bounce of each other.

I don't understand how to setup the P2 material inside a class, so it bounces against itself.

If anyone could help, that would be awesome :)

Link to comment
Share on other sites

Hi @enpu

I have pretty much everything working, but I can't figure out how to make the balls (created out of the ball class), to bounce against each other.

game.createClass('S05Ball', {
    
    init: function(x, y) {
        
        this.sprite = new game.Sprite('s05Ball.png');
        this.sprite.position.set(x, y);
        this.sprite.anchorCenter();
        this.sprite.addTo(game.scene.fg);
        
        this.body = new game.Body({
            mass: 1,
            ccdSpeedThreshold: 1,
            position: [
                this.sprite.position.x / game.scene.world.ratio,
                this.sprite.position.y / game.scene.world.ratio
            ]
        });
        
        this.body.velocity[1] = 1;
        this.body.restitution = 1;
        
        this.shape = new p2.Circle({
            radius: 16 / 2 / game.scene.world.ratio,
            material: new p2.Material()
        });
        
        this.body.addShape(this.shape);
        this.body.addTo(game.scene.world);
        
        game.scene.world.addContactMaterial(new p2.ContactMaterial(game.scene.wallBShape.material, this.shape.material, {
            restitution: 0.25,
            stiffness: Number.MAX_VALUE // We need infinite stiffness to get exact restitution
        }));
    },
    
    remove: function() {
        this.body.remove();
        this.sprite.remove();
    },
    
    update: function() {
        this.sprite.position.x = this.body.position[0] * game.scene.world.ratio;
        this.sprite.position.y = this.body.position[1] * game.scene.world.ratio;
        this.sprite.rotation = this.body.angle;
        
        if (this.sprite.position.y > 320) {
            //this.remove();
        }
    }
});

Thaaaanks!

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...