AS3 hitTestObject无法正常工作

时间:2018-08-03 13:37:08

标签: actionscript-3

我正在制作闪光灯,该键盘在键盘上移动了一个圆圈,并产生了撞在墙上的闪光灯。 但是方法“ hitTestObject”不起作用...

您能解决这个问题吗?

import flash.events.KeyboardEvent;
import flash.events.Event;

stage.addEventListener(KeyboardEvent.KEY_DOWN,atKeydown);
stage.addEventListener(KeyboardEvent.KEY_UP,atKeyup);

function atKeydown(e :KeyboardEvent) :void
{
    if(e.keyCode == 38) stage.addEventListener(Event.ENTER_FRAME,enterYUp);
    if(e.keyCode == 40) stage.addEventListener(Event.ENTER_FRAME,enterYDown);
    if(e.keyCode == 37) stage.addEventListener(Event.ENTER_FRAME,enterXLeft);
    if(e.keyCode == 39) stage.addEventListener(Event.ENTER_FRAME,enterXRight);
}

function atKeyup(e :KeyboardEvent) :void
{
    if(e.keyCode == 38) stage.removeEventListener(Event.ENTER_FRAME,enterYUp);
    if(e.keyCode == 40) stage.removeEventListener(Event.ENTER_FRAME,enterYDown);
    if(e.keyCode == 37) stage.removeEventListener(Event.ENTER_FRAME,enterXLeft);
    if(e.keyCode == 39) stage.removeEventListener(Event.ENTER_FRAME,enterXRight);
}

function enterYUp(e :Event) :void
{
    ball.y -= 10;
}
function enterYDown(e :Event) :void
{
    ball.y += 10;
}
function enterXLeft(e :Event) :void
{
    ball.x -= 10;
}
function enterXRight(e :Event) :void
{
    ball.x += 10;
}

if(ball.hitTestObject(wall) == true) trace("!!!!");

1 个答案:

答案 0 :(得分:-1)

function enterYUp(e :Event) :void
{
 var bool = checkHit("y", -10); // each frame checks for a hit, returns a Boolean (see the function below)
 carryOut(bool, "y", -10); // the movement is carried out based on the Boolean
}
function enterYDown(e :Event) :void
{
var bool = checkHit("y", +10); // you can send the "y" property, and where it wants to go.
 carryOut(bool, "y", +10);
}
function enterXLeft(e :Event) :void
{
var bool = checkHit("x", -10);
 carryOut(bool, "x", -10);
}
function enterXRight(e :Event) :void
{
 var bool = checkHit("x", +10);
 carryOut(bool, "x", -10);
}

function checkHit(_prop, _num):Boolean
{ 
 // This single function will run every frame, comparing the balls 'predicted position' 
  if((ball[_prop] + _num) <=  _numCheck)
  {
  // i might use hitTestPoint instead, but I hate using hitTestObject... it can act weird sometimes.
  return true;
  }
  else
  {
  return false;
  }
}


function carryOut(bool, _prop,_num):void
{
  if(bool)
 {
  trace("hit");
 }
 else
 {
  // if the Boolean returned false
  // ball[_prop] is ball.x or ball.y depending on if you sent "x" or "y".
  // it will ADD the _num you sent, so adding -10 is the same as subtracting.
  ball[_prop] += _num;
 }
}