PIXI 碰撞和边界

 边界:

// 限定了探险者的运动边界,contain(explorer,state)
contain(explorer,{x:28,y:10,width:488,height:480});

function contain(sprite,container){
    let collision = undefined;

    // left
    if(sprite.x < container.x){
        sprite.x = container.x;
        collision = "left";
    }

    // top
    if(sprite.y < container.y){
        sprite.y = container.y;
        collision = "top";
    }

    // right
    if(sprite.x + sprite.width > container.width){
        sprite.x = container.width - sprite.width;
        collision = "right";
    }

    // bottom
    if(sprite.y + sprite.height > container.height){
        sprite.y = container.height - sprite.height;
        collision ="bottom";
    }
    return collision;
}

碰撞

hitTestRectangle(explorer,blob);//explorer,blob都是精灵

// 检测碰撞:先计算出explorer和blob的中心位置坐标,
// 再计算explorer和blob的中心距离(vx,vy),
// 再计算出explorer和blob的中心相加的距离(combinedHalfWidths,combinedHalfHeights),
// 通过判断vx的绝对值和combinedHalfWidths的大小,vy的绝对值和combinedHalfHeights的大小来判断是否发生碰撞
function hitTestRectangle(r1,r2){
    let hit,combinedHalfWidths,combinedHalfHeights,vx,vy;

    hit = false;

    r1.centerX = r1.x + r1.width/2;
    r1.centerY = r1.y + r1.height/2;
    r2.centerX = r2.x + r2.width/2;
    r2.centerY = r2.y + r2.height/2;

    r1.halfWidth  = r1.width/2;
    r1.halfHeight = r1.height/2;
    r2.halfWidth  = r2.width/2;
    r2.halfHeight = r2.height/2;

    vx = r1.centerX - r2.centerX;
    vy = r1.centerY - r2.centerY;

    combinedHalfWidths  = r1.halfWidth  + r2.halfWidth;
    combinedHalfHeights = r1.halfHeight + r2.halfHeight;

    if(Math.abs(vx) < combinedHalfWidths && Math.abs(vy) < combinedHalfHeights){
        hit = true;
    }else{
        hit = false;
    }
    return hit;
}

这两个可以作为函数封装好

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值