Search code examples
flashmovedirectionbullet

ActionScript 3 - Initiating A Bullet Changes Direction With Character


I'm working on a side scroller that has a character that fires a bullet every time you hit spacebar, the problem I'm having is moving the bullet in the direction the character is facing (left or right).

I have a few of boolean variables to tell me which direction my character is facing: walkingRight | walkingLeft, so if my walkingRight == true, I want the bullet to travel +=10, and walkingLeft == true, bullet -= 10.

The problem is, when I fire facing left, the bullet moves left, but as soon as I turn right, that same bullets starts moving right.

Here is a snippet of AS3 code (Every Frame):

if(gamepad.fire2.isPressed){
   // initiate bullet
   var bullet = new Bullet();
   bullet.x = _player.x;
   bullet.y = _player.y;
   /*_boundaries.*/addChild(bullet);
   bullets.push(bullet);
}

for each(var bullet in bullets){
   if(walkingRight || idleRight || jumpingRight){
    bullet.x += 10;
    trace("Bullet - Moving Right");
   }
   else if(walkingLeft || idleLeft || jumpingLeft){
    bullet.x -= 10;
    trace("Bullet - Moving Left");
   }
}

I sure would appreciate any help from this as its for a college project.

Thanks


Solution

  • You may try something like this:

    First create this class:

    dynamic class BulletWrapper{
         private var bullet:DisplayObject = null;
         public function BulletWrapper( bullet:DisplayObject ){
             this.bullet = bullet;
         }
         public function getBullet():DisplayObject{
             return this.bullet;
         }
    }
    

    Then modify your code:

    if(gamepad.fire2.isPressed){
      // initiate bullet
       var bullet = new Bullet();
       bullet.x = _player.x;
       bullet.y = _player.y;
       /*_boundaries.*/addChild(bullet);
       var wrapper:BulletWrapper = new BulletWrapper( bullet );
       //storing as much information as related to bullet animation 
       wrapper.walkingStep = 0;
       wrapper.log = "No move";
       //-------------------------------
       if( walkingRight || idleRight || jumpingRight ){
           wrapper.walkingStep = 10;
           wrapper.log = "Bullet - Moving Right";
       }else if( walkingLeft || idleLeft || jumpingLeft ){
           wrapper.walkingStep = -10;
           wrapper.log = "Bullet - Moving Left";
       }
       //--------------------------
       bullets.push(wrapper);
    }
    
    for each(var wbullet:BulletWrapper in bullets){
       var bullet = wbullet.getBullet();
       bullet.x += wbullet.walkingStep;
       trace(wbullet.log);
    }