我正在尝试创建一个简单的hitTestObject,并查看正在使用Ball命中的屏幕上绘制的线条。如果是这样,它将擦除所有行并重新开始。我很亲密。 checkIt()函数是代码需要发生的地方,它清除了行但没有形成新的形状。
如何删除鼠标绘制的线条并在达到命中测试时重新开始?
var myshape:Shape;
myshape = new Shape();
myshape.graphics.lineStyle(12, 0xC807DE);
var alreadyDrawn:Shape;
alreadyDrawn = new Shape();
stage.addEventListener(MouseEvent.MOUSE_DOWN, activateDraw);
function activateDraw(event:MouseEvent):void
{
myshape.graphics.moveTo(mouseX,mouseY);
addChild(myshape);
stage.addEventListener(MouseEvent.MOUSE_MOVE, lineDraw);
function lineDraw(myevent:MouseEvent):void
{
stage.addEventListener(MouseEvent.MOUSE_UP, stopDraw);
function stopDraw(endevent:MouseEvent):void
{
alreadyDrawn = myshape;
stage.removeEventListener(MouseEvent.MOUSE_MOVE, lineDraw);
}
myshape.graphics.lineTo(mouseX,mouseY);
myevent.updateAfterEvent();
checkIt();
}
}
function checkIt()
{
if (alreadyDrawn.hitTestObject(Ball) == true)
{
trace("Hit The Balls");
myshape.graphics.clear();
myshape.graphics.lineStyle(12, 0xC807DE);
}
}
答案 0 :(得分:1)
你实际上有一个形状而不是两个,因为一旦你做alreadyDrawn=myshape
,你就会失去你附在的任何物体。你应该做alreadyDrawn.graphics.copyFrom(myshape.graphics);
,这会将所有笔划从参数复制到对象而不会丢失另一个实例。
接下来,如果您检测到点击率alreadyDrawn
,您似乎还需要停止绘图,为此,请从stopDraw(null);
致电checkIt()
。
接下来,在添加越来越多的时候,你没有清除所有听众。请参阅,如果您快速连续绘制几行(按下拖动释放),stopDraw
侦听器会被多次添加,甚至不会删除一次。要执行此操作,请在removeEventListener(MouseEvent.MOUSE_UP, stopDraw);
函数内使用stopDraw
并将添加行移至activateDraw
,因为拖动鼠标时会有多个“鼠标移动”事件,并且每个都会添加另一个侦听器你处理事件的时间。
最后,请不要在没有实际需要的情况下嵌套函数!
固定代码应为:
var myshape:Shape;
myshape = new Shape();
myshape.graphics.lineStyle(12, 0xC807DE);
var alreadyDrawn:Shape;
alreadyDrawn = new Shape();
stage.addEventListener(MouseEvent.MOUSE_DOWN, activateDraw);
function activateDraw(event:MouseEvent):void
{
myshape.graphics.moveTo(mouseX,mouseY);
addChild(myshape);
stage.addEventListener(MouseEvent.MOUSE_MOVE, lineDraw);
stage.addEventListener(MouseEvent.MOUSE_UP, stopDraw);
}
function lineDraw(event:MouseEvent):void
{
myshape.graphics.lineTo(mouseX,mouseY);
event.updateAfterEvent();
checkIt();
}
function stopDraw(event:MouseEvent):void
{
alreadyDrawn.graphics.copyFrom(myshape.graphics);
stage.removeEventListener(MouseEvent.MOUSE_MOVE, lineDraw);
stage.removeEventListener(MouseEvent.MOUSE_UP, stopDraw);
}
function checkIt()
{
if (alreadyDrawn.hitTestObject(Ball) == true)
{
trace("Hit The Balls");
myshape.graphics.clear();
myshape.graphics.lineStyle(12, 0xC807DE);
alreadyDrawn.graphics.clear(); // clear this too
stopDraw(null); // stop active draw, if any
}
}
答案 1 :(得分:0)
有趣的问题〜
我认为您可能忘记在moveTo
之后忘记clear
。
这是我的修复:
将mouseX
,mouseY
传递给checkIt
。
checkIt( mouseX, mouseY );
function checkIt( mouseX:Number, mouseY:Number ):void
{
if (alreadyDrawn.hitTestObject(Ball))//you don't need == true here
{
trace("Hit The Balls");
myshape.graphics.clear();
myshape.graphics.lineStyle(12, 0xC807DE);
myshape.graphics.moveTo(mouseX,mouseY);
}
}