Ryan
Ryan

Reputation: 10049

Actionscript 3: Increment a variable (++1)

The problem is in the addition of i. I have tried ++i, I have tried i=i+1 as well as i.tostring() and i++ but I still get the output as

hitting!1

How do I increment i?

Here's my code:

function mousePosition(inputEvent:MouseEvent)
{
    var i:Number = 0;
    var smiley:MovieClip = new Smiley();
    smiley.x = inputEvent.stageX;
    smiley.y = inputEvent.stageY;
    smiley.addEventListener(Event.ENTER_FRAME, smileyEnterFrame, false, 0, true);
    this.addChild(smiley);
    // ****************************** BELOW IS THE PROBLEM ******
        if (smiley.hitTestObject(RoundButton1) == true)
    {i=i+1;
        trace("hitting!"+ i);
    }
}

Upvotes: 1

Views: 2823

Answers (1)

fletch
fletch

Reputation: 1641

Your variable i only has scope within your mousePosition function, so each time you call mousePosition you are declaring a new i and setting it to 0. Try declaring your hitCounter variable outside of the function, so that it has a global scope.

var hitCounter:Number = 0;

function mousePosition(inputEvent:MouseEvent)
{
   ...
   if (smiley.hitTestObject(RoundButton1) == true)
   {
       hitCounter++;
       trace('hitting! ' + hitCounter);
   }
}

Give that a shot.

Upvotes: 5

Related Questions