0

So I want a unit to be able to randomly target a player unit or a players allies. I have all ally ships stored in an array and the player is on the stage separately.

Here is the code for the bullet creation, with the irrelevant stuff removed.

private function createBullet(): void {
    var rand = allies[Math.floor(Math.random()*allies.length)]; 

        _endX = rand.x 
        _endY = rand.y 

    }

With the code above I can make them target random ally ships, but I also want it to include the player ship (_player) when randomly selecting a target, but I cant add the player to the ally array so Im not really sure what to do.

1 Answer 1

1

When you multiply a random number by length of array, add plus one to length. If generated index is equal to the allies length, this means that "rand" is _player.

var randomIndex:int = Math.floor(Math.random() * (allies.length + 1));
var rand:*;
if (randomIndex == allies.length - 1)
    rand = _player;
else
    rand = allies[randomIndex];
...
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for the explanation, but using the method above I'm getting Error #1010: A term is undefined and has no properties.
I tested it a bit more and found the enemies will only shoot if there is an ally alive and they will only shoot at the player ship.
Try this: var randomIndex:int = Math.round(Math.random() * allies.length); var rand:*; if (randomIndex == allies.length) rand = _player; else rand = allies[randomIndex];

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.