AS3 - 使用空格键添加类的新实例

时间:2015-08-28 15:24:19

标签: actionscript-3 class addchild

我有2个类,Main和Rocket,我每次打空格键时都会尝试创建一个新的Rocket实例。这就是我现在所拥有的:

Main.as:

package  
{
import flash.display.MovieClip;
import flash.events.Event;
import flash.events.KeyboardEvent;
import flash.ui.Keyboard;

public class Main extends MovieClip
{       
    // player
    private var _player:MovieClip;

    // player settings
    private var _maxSpeed:Number = 5;
    private var _rotationSpeed:Number = 5;
    private var _thrust:Number = 0.5;
    private var _decay:Number = .97;        

    private var _currentSpeed:Number = 0;
    private var _speedX:Number = 0;
    private var _speedY:Number = 0;

    // keyboard flags
    private var _movingUp:Boolean = false;
    private var _movingLeft:Boolean = false;
    private var _movingRight:Boolean = false;
    private var _pressingSpace:Boolean = false;

    private var rocket:Rocket = new Rocket();
    /**
     * Constructor
     */
    public function Main() 
    {

        createPlayer();

        // add listeners
        stage.addEventListener(Event.ENTER_FRAME, enterFrameHandler);           
        stage.addEventListener(KeyboardEvent.KEY_DOWN, myOnPress); // ANY KEY



        stage.addEventListener(KeyboardEvent.KEY_UP, myOnRelease);      // ANY KEY  
    }

    /**
     * Creates player
     */
    private function createPlayer():void
    {
        _player = new Player();
        _player.x = stage.stageWidth / 2;
        _player.y = stage.stageHeight / 2;
        stage.addChild(_player);


    }

    /**
     * EnterFrame Handlers
     */
    private function enterFrameHandler(event:Event):void
    {
        // Rotate right or left
        if (_movingRight)
        {
            _player.rotation += _rotationSpeed;
        }

        if (_pressingSpace)
        {
            rocket.x = _player.x;
            addChild(rocket);

        }

        if (_movingLeft)
        {
            _player.rotation -= _rotationSpeed;
        }
        if (_movingUp)
        {


            trace(("Speed var before executing x"), + _speedX,  ("Speed var before executing y"), + _speedY);

            _speedX += _thrust * Math.sin(_player.rotation * (Math.PI / 180)); // as closer you are to 90 or -90 degrees in radians(+90* is 1 radian) the faster you accelarte to x or -x
            _speedY += _thrust * Math.cos(_player.rotation * (Math.PI / 180)); //as closer you are to 0 or 180 degrees in radians(+90* is 1 radian) the faster you accelarte to y

            trace(("the rad sin: ") + Math.sin(_player.rotation * (Math.PI / 180)));
            trace(_player.rotation);    
            trace(("Speed var x"), + _speedX,  ("Speed var y"), + _speedY);
            trace(("cos rad y ") + Math.cos(_player.rotation * (Math.PI / 180)));
            trace("current speed" + _currentSpeed);
        } 
        else{
            // Deccelerate when Up Arrow key is released
            // if you wanna stop right now: _speedX = 0;
            // if you wanna stop right now: _speedY = 0;
            _speedX *= _decay;
            _speedY *= _decay;
        }

        // Maintain speed limit
        _currentSpeed = Math.sqrt((_speedX * _speedX) + (_speedY * _speedY)); // using this method in order to turn negative (if there are) numbers into positive, then add them together to find combined speed.

        if (_currentSpeed > _maxSpeed) // if combined speed (x + y) exceeds max speed (5), divide max speed by current speed, which always will return a number below 1. then multiply that number to both y and x speed to slow down
        {
            _speedX *= _maxSpeed/_currentSpeed; // 
            _speedY *= _maxSpeed/_currentSpeed; // 
        }

        // Move _player based on calculations above
        _player.y -= _speedY; // What's y worth right now + add the speed of y
        _player.x += _speedX; // What's x worth right now + add the speed of x

    }

    /**
     * Key Press Handlers
     */
    public function myOnPress(event:KeyboardEvent):void
    {
        switch( event.keyCode )
        {
            case Keyboard.UP:
                _movingUp = true;
                break;

            case Keyboard.LEFT:
                _movingLeft = true;
                break;

            case Keyboard.RIGHT:
                _movingRight = true;
                break;

            case Keyboard.SPACE:
                _pressingSpace = true;
                break;  
        }
    }

    /**
     * Key Release Handlers
     */
    public function myOnRelease(event:KeyboardEvent):void
    {
        switch( event.keyCode )
        {
            case Keyboard.UP:
                _movingUp = false;
                break;

            case Keyboard.LEFT:
                _movingLeft = false;
                break;

            case Keyboard.RIGHT:
                _movingRight = false;
                break;

            case Keyboard.SPACE:
                _pressingSpace = false;
                break;  
        }
    }

 }

}

       Rocket.as:
package 
{
    import flash.display.Bitmap;
    import flash.display.Sprite;

    public class Rocket extends Sprite
    {

        [Embed(source = "red_dot.gif")] public static var pictureClass:Class;      // save image to class

        private var myBitmap:Bitmap = new pictureClass; // create bitmap data


        public function Rocket() 
        {
            addChild(myBitmap); // add the bitmap
        }

    }

}

所以现在,当我按下空格键时,带有位图的类会添加到带有addChild的屏幕上,并且该图像的x与播放器&s; sx相同(我有一个可以移动的播放器) 。下次我点击空格键(不释放空格)时,只需跟随我到我的播放器的任何地方。我想要做的是,每当我点击空格键到我的播放器的x所在的位置时添加一个新的图像火箭。顺便说一下,我想能够操纵这些新创建的图像,所以请将其考虑在内。 谢谢。

1 个答案:

答案 0 :(得分:2)

使用new关键字进行实例化。目前,在代码顶部创建一个名为rocket的类级别var,并在同一行中实例化Rocket。所以只创造了一枚火箭。您使用addChild,它只是反复添加相同的项目(基本上没有明显的效果)。

你需要做的是创建一个阵列/矢量来存储所有火箭,并在按下空格键时实例化(或者,如果你想限制火箭的创建频率,请在你的输入框处理程序中) )。

首先,将您的班级rocket var替换为Vector以存储所有火箭:

private var rockets:Vector.<Rocket> = new Vector.<Rocket>();
//vectors and the same as arrays, only all members have to be of the specified class (or inherit from it)

通过这种方式,您可以轻松快速地迭代所有火箭。

然后,当你点击空格键时,创建一个new火箭并将其添加到屏幕和数组/矢量

    case Keyboard.SPACE:
        _pressingSpace = true;
        var rocket:Rocket = new Rocket();
        rocket.x = player.x;
        addChild(rocket);
        rockets.push(rocket);

或者,您可以使用基于时间的方法来限制射击/产生火箭的频率。而不是上面的代码,你将在输入框处理程序中执行此操作。

首先,创建一个类级别var,以便下次允许火箭发射时保持:

private var rocketTime:int;

然后,修改输入框处理程序,如下所示:

    if (_pressingSpace)
    {
        if(flash.utils.getTimer() >= rocketTime){
            var rocket:Rocket = new Rocket();
            rockets.push(rocket);
            rocket.x = player.x;
            addChild(rocket);
            rocketTime = flash.utils.getTimer() + 500; //say you want to wait at least half a second before spawning a new rocket.
        }
    }

在某些时候,你必须检查火箭是否与某物发生碰撞。 您希望在输入框处理程序中执行此操作。如果你确定它是碰撞的,你需要移除火箭。

假设您有一个名为enemies的敌人阵列/矢量图。在您的输入框处理程序中,您需要这些内容:

//loop backwards through your rockets array
for(var i:int=rockets.length-1;i >= 0;i--){
    //you'll want to to move your rockets, however you do that
    rockets[i].y -= 5; 

    //next, check if this rocket collides with any enemies
    for(var j:int = enemies.length-1; j >= 0; j--){
        if(rockets[i].hitTestObject(enemies[j])){
            //yes, it collides! remove the rocket and the enemy
            removeChild(enemies[j]);
            removeChild(rockets[i]);

            enemies.splice(j,1); //take it out of the array
            rockets.splice(i,1);

            //when you splice an array, you shift all the indexes
                //this is why you need to iterate backwards instead of forwards        
            //because we've spliced, you can no longer use rockets[i] or enemies[j] after this point in the loops
                //they will either be null, refer to different items than they did before you spliced
            break; //don't keep checking enemies in this for loop as we've removed the rocket
        }
    }
}