如何让物体反弹?

时间:2012-02-15 21:17:37

标签: flash

for (var k:int = 0; k < 1; k++)
        {
            money = new Money;
            money.x = X[chooseSpawnPoint()];
            money.y = moneysourceY;
            money.dx = RandomRange(-5,5);
            money.dy = RandomRange(-5,5);
            Config.CurrentStage.addChild(money);

            moneyVector.push(money);
        }

private function Update(evt:Event)
    {

        for (var i:int = 0; i < moneyVector.length; i++)
        {               
            moneyVector[i].x += moneyVector[i].dx;
            moneyVector[i].y += moneyVector[i].dy;
            if (moneyVector[i].hitTestObject(character))
            {
                Config.CurrentStage.removeChild(moneyVector[i]);
                moneyVector.splice(i, 1);
                moneyscore +=  400;
                moneytext.text = "Money : " + moneyscore.toString();
                money = new Money  ;
                money.dx = RandomRange(-5,5);
                money.dy = RandomRange(-5,5);
                money.x = X[chooseSpawnPoint()];
                money.y = moneysourceY;
                Config.CurrentStage.addChild(money);
                moneyVector.push(money);

            }
            if ( moneyVector[i].x < 0 ) {
                moneyVector[i].x = moneyVector[i].x + -1 * moneyVector[i].dx //<-- cannot bounce back
            }

        }
    }

当对象与墙碰撞时,object.Y增加但是object.X保持不变而不是object.X也应该增加。 如何让物体反弹?

1 个答案:

答案 0 :(得分:0)

当X小于0时,你只是让它反弹...所以发生的事情就是物体击中墙(x小于0)后移回到0(实际上是0,因为你有如果它小于0)然后开始再次回到墙上,直到它小于0(几乎立即)。所以你会看到物体刚刚卡在墙上(x = 0)。

我倾向于接近这种方法的一种方法是存储+1或-1的不同方向变量。一旦对象通过0(x <0),我将方向设置为+1。一旦物体撞到远处,我想向右移动,我将方向设置回-1。然后,每当我通过移动速度增加x位置时,我乘以方向,这只会改变方向而不是速度。

private function Update(evt:Event) 
{ 

    for (var i:int = 0; i < moneyVector.length; i++) 
    {     
       // Figure out what direction to move           
        if ( moneyVector[i].x < 0 ) { 
            direction = 1; 
        } else if(moneyVector[i].x > maxX) {
             direction = -1;
        }
        // Multiply by direction to move the correct way
        moneyVector[i].x += moneyVector[i].dx * direction;
        moneyVector[i].y += moneyVector[i].dy; 
        if (moneyVector[i].hitTestObject(character)) 
        { 
            Config.CurrentStage.removeChild(moneyVector[i]); 
            moneyVector.splice(i, 1); 
            moneyscore +=  400; 
            moneytext.text = "Money : " + moneyscore.toString(); 
            money = new Money  ; 
            money.dx = RandomRange(-5,5); 
            money.dy = RandomRange(-5,5); 
            money.x = X[chooseSpawnPoint()]; 
            money.y = moneysourceY; 
            Config.CurrentStage.addChild(money); 
            moneyVector.push(money); 

        } 

    } 
} 

不要忘记将方向存储为每个moneyVector索引的变量,并设置你想要的maxX而不是我所拥有的“maxX”