Forum Topic: Random Enemies Help

(83 views • 2 replies)

This topic is 1 page long.

<< < > >>
None

cheese1756

Reply To Post Reply & Quote

Posted at: 6/10/09 05:22 PM

cheese1756 NEUTRAL LEVEL 02

Sign-Up: 04/22/09

Posts: 27

Ok so I want to make a game where you are a blue square or something and you have to avoid the red circles while collecting powerups and being timed. How could I make red circles appear randomly instead of them popping up in the same place every time someone plays the game? What I mean is how could I make it so that the first red circle might appear in the top left corner OR the bottom right?


None

Neo-13

Reply To Post Reply & Quote

Posted at: 6/10/09 05:47 PM

Neo-13 LIGHT LEVEL 21

Sign-Up: 06/09/07

Posts: 1,475

Math.random()

BBS Signature

None

Afro-Ninja

Reply To Post Reply & Quote

Posted at: 6/10/09 05:52 PM

Afro-Ninja EVIL LEVEL 38

Sign-Up: 03/02/02

Posts: 13,469

Use random numbers. Let's say you wanted the enemy's x position to be between 0 and 500. You use the function

Math.random();

which will return a number between 0 and 1. Multiply that number by 500 to get a number between 0 and 500, then assign it to your enemy

var randomX:Number = Math.random()*500;
enemy.x=randomX;

You would need to do it for y as well. if you don't want the enemy to appear off the screen you need to adjust the formula to take the enemy's height and width into account

Alternatively if you wanted the enemy to appear in set positions (IE, top left bottom or right), then store those points in an array

var startPositions:Array = new Array();
startPositions.push(new Point(10,10));
startPositions.push(new Point(400,10));
startPositions.push(new Point(10,400));
startPositions.push(new Point(400,400));

then pick out a random spot in the array to use

var randomStartIndex:uint = Math.floor(Math.random()*startPositions.length);
var randomPoint:Point = startPositions[randomStartIndex];
enemy.x = randomPoint.x;
enemy.y = randomPoint.y;

this code is in AS3, if you're using as2 it will be slightly different (mostly just the use of _x and _y instead of x and y);

BBS Signature

All times are Eastern Standard Time (GMT -5) | Current Time: 09:48 AM

<< Back

This topic is 1 page long.

<< < > >>
You need a Grounds Gold Account to post on the NG BBS! If you don't have one, click here to sign up now! It's fast, free, and easy — and opens up tons of great NG features!