javascriptcollision-detectionhittestpixi.js

'Sprite from Texture' not taking Hit Area Polygon


I have a sprite with a texture defined as follows:

// Create sprite
spriteObj = new PIXI.Sprite(tileTexture);
spriteObj.interactive = true;

spriteObj.anchor = new PIXI.Point(0,0.5);

spriteObj.click = function(mouseData) {
    alert("Clicked Me!");
};

I'm then creating a hit area using a polygon as follows:

polyCords = new PIXI.Polygon([
    new PIXI.Point(xPos,yPos),
    new PIXI.Point(xPos + (tileWidth / 2), yPos + (tileHeight/2)),
    new PIXI.Point(xPos + tileWidth, tyPos),
    new PIXI.Point(xPos + tileWidth / 2, this.yPos - (tileHeight/2)),
]);

I assign the polygon as the hit area of the sprite:

spriteObj.hitArea = polyCords;

and then add the sprite to the stage:

stage.addChild(spriteObj);

So far so good. However, the hit area is not correct. To test the co-ordinates of the hit area are correct, I'm using the graphics object to draw a coloured shape representing the polygon as follows:

testTile = new PIXI.Graphics();
testTile.beginFill(0x21B837);
testTile.drawShape(polyCords);
testTile.endFill();
stage.addChild(testTile);

The shape draws (perfectly), the hit area that I would expect but the actual hit area doesn't correspond to the shape I have drawn!


Solution

  • The following TypeScript works fine with PIXI v3.0.3

    SpriteFromPoints(graphics, points /*PIXI.Point[]*/, bounds /*{x, y, width, height}*/, isInteractive) {
        var polygon = graphics.drawPolygon(points);
        var zoneSprite = new PIXI.Sprite(polygon.generateTexture(1, (<any>PIXI).SCALE_MODES.DEFAULT));// no d.ts yet for v3
        zoneSprite.position.x = bounds.x;
        zoneSprite.position.y = bounds.y;
        zoneSprite.interactive = isInteractive || false;
        if (zoneSprite.interactive) {
            // can't assign the polygon from above for whatever reason
            // seems to be a different type and doesn't have the contains method
            zoneSprite.hitArea = new PIXI.Polygon(points); 
        }
        return zoneSprite;
    }
    

    Adding the sprite returned, the hit area is what I expected.