user1104229
user1104229

Reputation: 1

ActionScript 3.0 Changing Direction

Alright let me make this clear. I am just doing out of interest. This is not a homework. I am doing it because I am interest in writing the ActionScript. I saw a guy website doing something amazing so I tried to copy and I want to do this:

Oh by the way you need to make a symbol and need to export for ActionScript and class name is "ball". And the button instant name is:bButton. So here's the script I wrote so far.

var boundaryRight:Number = stage.stageWidth;
var boundaryLeft:Number = 0;
var balls:Array;
var reverseRight:Number = 0;
var reverseLeft:Number = stage.stageWidth;

init();

function init(){
    balls = new Array();
    for(var i:Number = 0; i<10; i++){
        var myBall:ball = new ball();
        myBall.x=(Math.random()*boundaryRight);
        myBall.y=50+i*40;
        addChild(myBall);
        balls.push(myBall);
    }
}

addEventListener(Event.ENTER_FRAME,moveBall);

function moveBall(e:Event){
    for(var i:Number = 0;i<10;i++){
        var myBall:ball = balls[i];
        myBall.x-=20;
        if(myBall.x<boundaryLeft){
            myBall.x=boundaryRight;
        }
    }
}

As you can see that code made the multiple ball go to left and looping over and over again. So here's what I want to do. I want to make a button and when I click the button it'll change direction like click and it change direction to right. I click it again and it'll go left again. How do I write the code for that?

Upvotes: 0

Views: 803

Answers (1)

Diode
Diode

Reputation: 25145

Use two global variables direction and speed.

var direction:Number = 1; var speed:Number = 20;

Instead of giving myBall.x-=20;

Give myBall.x += ( direction * speed );

In the click handling function of the button

Give direction *= -1;

You can also change speed like this.

Upvotes: 2

Related Questions