如何为AS3中的代码中绘制的矩形创建命中框

时间:2015-10-26 04:27:16

标签: actionscript-3 timer shapes

所以我有一个程序,它以随机颜色生成矩形,然后继续下降到屏幕上。我还有一个播放器根据你点击的按钮改变颜色。问题是让HitTestObject处理从代码中提取的对象。 这是代码:

  import flash.geom.ColorTransform;
import flash.events.TimerEvent;

var rectangle:Shape = new Shape;
var RecTimer:Timer = new Timer(5);
var RecSTimer:Timer = new Timer(800);
var collision:Timer = new Timer(10,1000);
collision.start()
RecTimer.addEventListener(TimerEvent.TIMER, onTimer);
RecTimer.start();
RecSTimer.addEventListener(TimerEvent.TIMER, onSpawnTimer);
RecSTimer.start();
collision.addEventListener(TimerEvent.TIMER, fcollision)


function fcollision(e:TimerEvent):void {
    if (mcPLayer.hitTestObject (rectangle)) {
        trace("hit")
    }
}


var rectangles:Array = []; // a list of all the rectangles we've made so far
 function spawnRectangle():void {
    var rectangle:Shape = new Shape();
    rectangle.graphics.beginFill(randomColor()); // choosing the colour for the fill, here it is red
    rectangle.graphics.drawRect(0, 10, 480, 45.49); // (x spacing, y spacing, width, height)
    rectangle.graphics.endFill();
    addChild(rectangle); // adds the rectangle to the stage
    rectangles.push(rectangle); // adds the rectangle to our list of rectangles
     var rect:Rectangle = rectangle.getBounds(rectangle);


}
var colors:Array = [0xFF0000, 0x00FF00, 0x0000FF];

function randomColor():uint
{
    return colors[int(Math.random()*colors.length)];
}
function moveAllRectangles():void {
    for each (var rectangle:* in rectangles) {
            rectangle.y +=2;
        if (rectangle.y == 550){
            removeChild(rectangle)
        }

                    }

    }

function onTimer(e:TimerEvent):void {
        moveAllRectangles();

}
function onSpawnTimer(e:TimerEvent):void {
    spawnRectangle();
}
btnRed.addEventListener(MouseEvent.CLICK, fred);
btnGreen.addEventListener(MouseEvent.CLICK, fgreen);
btnBlue.addEventListener(MouseEvent.CLICK, fblue);

function fred (e:MouseEvent):void{
 var myColorTransform = new ColorTransform();
myColorTransform.color = 0xFF0000;
mcPLayer.transform.colorTransform = myColorTransform;
}

function fgreen (e:MouseEvent):void{
 var myColorTransform = new ColorTransform();
myColorTransform.color = 0x00FF00;
mcPLayer.transform.colorTransform = myColorTransform;
}
function fblue (e:MouseEvent):void{
 var myColorTransform = new ColorTransform();
myColorTransform.color = 0x0066CC;
mcPLayer.transform.colorTransform = myColorTransform;
}

function delayedFunctionCall(delay:int, func:Function) {
    var timer:Timer = new Timer(delay, 1);
    timer.addEventListener(TimerEvent.TIMER, func);
    timer.start();
}

1 个答案:

答案 0 :(得分:0)

您有一个名为rectangle的全局范围变量,但除了碰撞测试功能外,似乎不会使用它。您应该检查rectangles数组中的形状:

function fcollision(e:TimerEvent):void {
    for each(var rectangle:Shape in rectangles)
    {
        if (mcPLayer.hitTestObject (rectangle)) {
            trace("hit")
        }
    }
}