Search code examples
actionscript-3flashmovieclipstage

AS3 - Placing movie clip at specified coordinates


I'm making a top down shooter game as project for a college assignment in which I have very little time left to complete.

I'm trying to get the enemy movieclip to spawn off stage, I have setup a function to create a random number for the x and y position and then stored each in a var, but I cant use the two var's for the coordinates, I get 3 errors:

Main.as, Line 33 1120: Access of undefined property enemy.

Main.as, Line 33 1137: Incorrect number of arguments. Expected no more than 0.

Main.as, Line 34 1120: Access of undefined property enemy.

Lines 33 - 34 Code from Main.as:

enemy = new Enemy(stage, xPos, yPos);
this.stage.addChild(enemy);

The xPos and yPos vars created on lines 18 and 19 respectively:

public var xPos:Number;
public var yPos:Number;

xPos and yPos are given values in the function spawnPos:

public function spawnPos()
    {
        var a:Number = Math.round(Math.random()*5);
        var aNum:Number;

        if (a <= 3)
        {
            aNum = Math.ceil(Math.random()*20) + 640;
            xPos = aNum;
            aNum = Math.ceil(Math.random()*20) + 480;
            yPos = aNum;


        }
        else if (a >= 2)
        {
            aNum = Math.ceil(Math.random()*-20) + 0;
            xPos = aNum;
            aNum = Math.ceil(Math.random()*-20) + 0;
            yPos = aNum;
        }
    }

And the spawnPos function is declared to run on line 32 just before the enemy is created:

spawnPos();

Help would be greatly appreciated, many thanks and hope all is having a great start to the new year. :)


Solution

  • Fixed and working

    Small changes were made to both the Main.as and Enemy.as as follows:


    Main.as

    The changes made here were to the statement of defining the enemy. It was

    enemy = new Enemy(stage, xPos, yPos);

    I removed the stage argument but kept the two variables xPos and yPos and made it a variable.

    var enemy:Enemy = new Enemy(xPos, yPos);

    I also removed where I called the spawnPos() function.


    Enemy.as

    I moved the spawnPos() function from Main.as to here and called it in the constructor code so it's only run when the enemy varible is.

    I then amended the class definition and added the arguments I wanted to be passed

    public function Enemy(xPos : Number, yPos : Number)