Search code examples
functionactionscript-3mouseeventkeyboard-eventskeycode

ActionScript 3 - Reloading Ammo


I am new about ActionScript 3.0 and I am creating a shooting game. My problem is about reloading the gun, of course when the ammo reaches 0, you have to reload. After pressing 'R' the bullet text goes back to 12 but when I Mouse Click, it will return again to 0.

import flash.events.MouseEvent;
import flash.events.KeyboardEvent;

var bulletCount:int = 13;
var bullets:int = 12;
var bulletEmpty:int = 0;

stage.addEventListener(MouseEvent.CLICK, bulletcount);
stage.addEventListener(KeyboardEvent.KEY_DOWN, keyDownHandler);

function bulletcount(evt:MouseEvent):void
{
    bulletCount--;
    Bullet1.text = String(bulletCount);

    if(bulletCount <= 0)
    {
        stopcount();
    }
}

function stopcount():void
{
    Bullet1.text = String(bulletEmpty);
}

function keyDownHandler(evt:KeyboardEvent):void
{
    if(evt.keyCode == 82) 
    {
    //Reload (using key 'R')
    Bullet1.text = String(bullets);
    }
}

Thanks in advance!


Solution

  • The reason why after pressing 'R' the bullet text goes back to 12 is because that value bullets isn't being being changed anywhere. It's always going to state 12 because that is the value you assigned it.

    When you mouse click the reason why it is going back to 0 is because the bulletCount variable is now at 0 after it being decremented in the Mouse Event:

     bulletCount--;
    Bullet1.text = String(bulletCount);
    
    if(bulletCount <= 0)
    {
        stopcount();  //bulletCount is now going to equal 0
    }
    

    to fix this add this inside the if statement or wherever you reload

    if(bulletCount <= 0)
    {
        stopcount();
        bulletCount += 12; // add the value back to the variable.
    }
    

    Also not sure why you have two variables for the bullets one will do just fine.