AS3 hittesting并没有真正的工作(嵌套)并没有、嵌套、工作、hittesting

2023-09-09 21:53:02 作者:提笔落惆怅

我有一个坦克。

我有一个英雄(控制字符)。

I got a hero (controllable character).

该箱具有一个嵌套的movieclip其具有非常薄的表面积

The tank has a nested movieclip which has a very thin surface area.

然而,事情检测时,它甚至没有触及英雄的碰撞。

Yet, the thing detects a collision when it's not even touching the hero.

public class tank_sight extends MovieClip
{
    private var _root:MovieClip;

    public function tank_sight() 
    {
        addEventListener(Event.ADDED, beginClass);
    }

    private function beginClass(event:Event):void
    {
        _root = MovieClip(root);
        addEventListener(Event.ENTER_FRAME, loop);
    }

    private function loop(event:Event):void
    {
        if(this.hitTestObject(_root.hero.hitbox))
        {
            this.gotoAndStop(2);
            trace("HIT");
            fire();
        }
        else
        {
            this.gotoAndStop(1);
        }
    }

    private function fire():void
    {
        var shell:Shell = new Shell(x, y, rotation - 180);
        _root.addChild(shell);
    }
}

什么是错?我不明白这一点。

What's wrong? I don't get it.

编辑:视觉是旋转的,所以这可能是为什么。我试图用这个code在播放器类:

Sight is rotating, so that's probably why. I tried using this code on the player class:

    point = _root.tanks.barrel.sight.localToGlobal(new Point());

        if(this.hitTestPoint(point.x, point.y, false))
                {
                    trace("HIT");
                }

不过,这并不工作..它从来没有痕迹HIT,除非我站在一些奇怪的位置,在特定的时间。

But it doesn't work.. It never traces "HIT", unless I stand in some weird location at certain times.

推荐答案

hitTestObject 适用于嵌套的对象还(有不同的父显示对象),你应该检查的逻辑你的游戏,和做一些测试。

hitTestObject works with nested objects also (display objects that have different parents), you should check logic of your game, and do some tests.

简单的例子:

var squareHolder:Sprite = new Sprite();
var squareInner:Shape = new Shape();
var hitHolder:Sprite = new Sprite();
var hitCircle:Shape = new Shape();

hitCircle.graphics.beginFill(0x990000);
hitCircle.graphics.drawCircle(0, 0, 20);

squareInner.graphics.beginFill(0x009900);
squareInner.graphics.drawRect(0, 0, 40, 40);

addChild(squareHolder);
squareHolder.addChild(squareInner);
squareHolder.x = 200;
squareHolder.y = 100;
squareInner.x = 50;
squareInner.y = 50;

stage.addChild(hitHolder);
hitHolder.addChild(hitCircle);
hitCircle.transform.matrix = new Matrix(1, 0.5, 0.5, 1, 30, 30);

stage.addEventListener(MouseEvent.MOUSE_MOVE, function (e:MouseEvent):void {
    hitHolder.x = e.stageX;
    hitHolder.y = e.stageY;

    if (hitCircle.hitTestObject(squareInner)) {
        trace("Ding!");
    }
});

不管你做什么用 hitCircle (可见=假,trasparent填写,转换),它仍然可以工作。

Whatever you do with hitCircle (visible=false, trasparent fill, transformations) it will still work.