[Solved] Resize physics sprite causes offset to physics shape

Hello,

I’m using Cocos2d-x v3.7 (JavaScript) with Chipmunk Physics.
To add a physics sprite I am doing this:

this.carSprite = new cc.PhysicsSprite.create("#car.png");

// OLD METHOD
var carSize = this.carSprite.getContentSize();

// Create and add the car's physics body 
var carBody = new cp.Body(1, cp.momentForBox(1, carSize.width, carSize.height));
this.space.addBody(carBody);

// Create and add the car's physics shape
var carShape = new cp.BoxShape(carBody, carSize.width, carSize.height);
this.space.addShape(carShape);

this.carSprite.setBody(carBody);
playSceneSpriteSheet.addChild(this.carSprite);

I’m not sure if this is the best way to add a physics sprite but it works fine and produces this:

Now I want to resize the physics sprite based on dimensions of my map so I do this:

this.carSprite = new cc.PhysicsSprite.create("#car.png");
    
// NEW METHOD
var carSize = this.carSprite.getContentSize();
var spaceForCar = [math to calculate allotted space];
var scaleCarSize = spaceForCar / carSize.height;
this.carSprite.setScale(scaleCarSize);
this.carSprite.setContentSize(cc.size(carSize.width * scaleCarSize, carSize.height * scaleCarSize));
carSize = this.carSprite.getContentSize(); // new contentSize

// Create and add the car's physics body 
var carBody = new cp.Body(1, cp.momentForBox(1, carSize.width, carSize.height));
this.space.addBody(carBody);

// Create and add the car's physics shape
var carShape = new cp.BoxShape(carBody, carSize.width, carSize.height);
this.space.addShape(carShape);

this.carSprite.setBody(carBody);
playSceneSpriteSheet.addChild(this.carSprite);

And this is produced:

Any idea how to align and centre the physics shape to the physics body after modifying the sprite size?

@pandamicro any tips or idea would be much appreciated.

Could the issue be because physics body doesn’t support scaling?

When I comment out this line:

// this.carSprite.setContentSize(cc.size(carSize.width * scaleCarSize, carSize.height * scaleCarSize));

So I don’t modify the car’s contentSize and then modify this line:

var carShape = new cp.BoxShape(carBody, carSize.width - scaleDifferenceOfWidth, carSize.height - scaleDifferenceOfHeight);

I can set the shape size while still keeping the anchors centered. It works perfectly fine this way :slight_smile: