我试图弹跳球。我使用这个example:
但是我没有处理类文件,我正在尝试使用框架代码。这就是我到目前为止所做的。
import flash.display.MovieClip;
import flash.display.Stage;
import flash.events.Event;
import flash.events.KeyboardEvent;
import Ball;
var nSpeedX:Number;
var nSpeedY:Number;
var nStageWidth:Number = 500;
var nStageHeight:Number = 400;
var NSpeedX:Number;
var NSpeedY:Number;
var mcBallContainer:MovieClip;
var MCBallA:MovieClip;
var MCBallB:MovieClip;
var nNumBalls:Number = 1;
stage.addEventListener(Event.ENTER_FRAME,BallCollision);
function BallCollision(oly:Event) {
mcBallContainer = new MovieClip ( ) ;
mcBallContainer.x = mcBallContainer.y = 0;
stage.addChild(mcBallContainer);
this.addEventListener ( Event.ENTER_FRAME, enterFrameHandler );
for (var i = 0; i < nNumBalls; i++)
{
var mcBall:Ball = new Ball ( Math.floor ( ( Math.random() * 1 ) - 4 ), Math.floor ( ( Math.random() * 12 ) - 4 ) );
mcBall.x = Math.random() * nStageWidth;
mcBall.y = Math.random() * nStageHeight;
mcBallContainer.addChild ( mcBall );
}
stage.removeEventListener(Event.ENTER_FRAME,BallCollision) //Fixed
}
function enterFrameHandler(oly:Event) {
for ( var i = 0; i < mcBallContainer.numChildren; i++ )
{
var mcBall1:* = mcBallContainer.getChildAt( i );
for ( var j = i + 1; j < mcBallContainer.numChildren; j++ )
{
var mcBall2:* = mcBallContainer.getChildAt( j );
var nDistX:Number = Math.abs ( mcBall1.x - mcBall2.x );
var nDistY:Number = Math.abs ( mcBall1.y - mcBall2.y );
var nDistance:Number = Math.sqrt ( nDistX * nDistX + nDistY * nDistY );
if ( nDistance < 20 )
{
solveBalls ( mcBall1, mcBall2 );
}
}
}
//
function solveBalls ( MCBallA:MovieClip, MCBallB:MovieClip ) : void{
var nX1:Number = MCBallA.x;
var nY1:Number = MCBallA.y;
var nDistX:Number = MCBallB.x - nX1;
var nDistY:Number = MCBallB.y - nY1;
var nDistance:Number = Math.sqrt ( nDistX * nDistX + nDistY * nDistY );
var nRadiusA:Number = MCBallA.width/2;
var nRadiusB:Number = MCBallB.width/2;
//var nRadius:Number = 10;
var nNormalX:Number = nDistX/nDistance;
var nNormalY:Number = nDistY/nDistance;
var nMidpointX:Number = ( nX1 + MCBallB.x )/2;
var nMidpointY:Number = ( nY1 + MCBallB.y )/2;
MCBallA.x = nMidpointX - nNormalX * nRadiusA;
MCBallA.y = nMidpointY - nNormalY * nRadiusA;
MCBallB.x = nMidpointX + nNormalX * nRadiusB;
MCBallB.y = nMidpointY + nNormalY * nRadiusB;
var nVector:Number = ( ( MCBallA.nSpeedX - MCBallB.nSpeedX ) * nNormalX )+ ( ( MCBallA.nSpeedY - MCBallB.nSpeedY ) * nNormalY );
var nVelX:Number = nVector * nNormalX;
var nVelY:Number = nVector * nNormalY;
MCBallA.nSpeedX -= nVelX;
MCBallA.nSpeedY -= nVelY;
MCBallB.nSpeedX += nVelX;
MCBallB.nSpeedY += nVelY;
}
}
我的代码正在运作,但是球的数量超过应有的数量。球不会相互碰撞。我的代码有什么问题??
更新感谢@Organis