Search code examples
actionscript-3flash-cs4

Adding text to a dynamic text field randomly in as3


i have a text field called Moneytxt and i want it so when u click on a box it somtimes adds 200 and somtimes adds 100 ( also i would like it to add up in numerical value example: if it adds 100 and it has 200 it equals 300 not 200100) . I also have penniestxt where sometimes it adds 30 and somtimes it adds 40.

this is the code (box getting added is not included or addeventlistener)

public function boxclick(event:MouseEvent):void {
            var _box:Box=event.currentTarget as Box;
            logtxt.appendText(" You collected the box");
            Moneytxt.random.appendText("100")
            Moneytxt.random.appendText("200")
            penniestxt.random.appendText("40")


            boxAmount--;

            removeChild(_box);
        }

Solution

  • The appendText method does exactly what it says--it appends text to the end of the text in the textfield--which is why you're getting "200100" instead of "300.

    To have the numbers add together you need to keep the money amount stored as a Number or int.

    var money:int = 0;
    money += 100;
    money += 200;
    Moneytxt.text = String(money);
    

    Note that you'll probably have to cast the value to a String when you assign it to the text field text.

    To do the random value, you can use Math.random(). It returns a number between 0 and 1. You can use that value to determine if you add 100 or 200.

    var money:int = 0;
    public function boxclick(event:MouseEvent):void {
        var randVal:Number = Math.random();
        if(randVal >= 0.5){
            money += 100;
        } else {
            money += 200;
        }
    
       Moneytxt.text = String(money);
    }