简体   繁体   中英

Resizing a sprite that has a custom physics file? (P2/Phaser)

I have a circular sprite (a pinball) with a Lime / Corona JSON physics file (exported from PhysicsEditor). The purpose of this file is so that the hitbox is actually circular.

It's working fine (for those not familiar with coffeescript, the @ just means this )

# in preload
@load.physics 'ball_physics', @Assets.ball_physics

# in create
@ball = @add_p2_sprite @ball_start_x, @ball_start_y, 'ball'
@ball.body.clearShapes()
@ball.body.loadPolygon 'ball_physics', 'ball'

The problem is that I cannot scale or resize the ball without messing up the hitbox. It seems like it always works off the original size. Is there any way to update this dynamically?

For example, here is using a non-resized sprite:

在此处输入图片说明

And here is with a sprite scaled to 0.5, 0.5:

在此处输入图片说明

Is there any way to do this other than creating new png and JSON files for the sprite?


here's a response to the comment, turning on debugMode so I see hitboxes outlined and scaling the ball before applying the physics file:

@ball =  @add.sprite @ball_start_x, @ball_start_y, 'ball'
@ball.scale.x = 2
@ball.scale.y = 2
@physics.p2.enable @ball, true
@add_physics_file(@ball, 'ball_physics', 'ball')
@collide_world_bounds(@ball)

The hitbox has not re-scaled:

在此处输入图片说明

I found a megmut user code, I tried it and it worked perfectly, you could try it:

function resizePolygon(originalPhysicsKey, newPhysicsKey, shapeKey, scale){
   var newData = [];
   var data = this.game.cache.getPhysicsData(originalPhysicsKey, shapeKey);

   for (var i = 0; i < data.length; i++) {
       var vertices = [];

       for (var j = 0; j < data[i].shape.length; j += 2) {
          vertices[j] = data[i].shape[j] * scale;
          vertices[j+1] = data[i].shape[j+1] * scale; 
       }

       newData.push({shape : vertices});
   }

   var item = {};
   item[shapeKey] = newData;
   game.load.physics(newPhysicsKey, '', item);

}

Just use:

    function preload() {
       game.load.image('contra2', 'contra2.png');

       game.load.physics('physicsData', 'sprites.json');
    }

    function create() {
       game.physics.startSystem(Phaser.Physics.P2JS);

       var scale = 1.5;
       resizePolygon('physicsData', 'robot', 'contra2', scale)

       contra = game.add.sprite(400, 300, 'contra2');
       contra.scale.setTo(scale, scale);

       game.physics.p2.enable(contra, true);

       contra.body.clearShapes();
       contra.body.loadPolygon('robot', 'contra2');
   }  

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM