dcsimg
A Flash Developer Resource Site

Results 1 to 3 of 3

Thread: Random Position Within Specific Area

  1. #1
    Junior Member
    Join Date
    Sep 2012
    Posts
    9

    Random Position Within Specific Area

    Hey. So, what I'm trying to do is create an enemy at a random position, but inside these coordinates:
    X: Between -30 and 1580
    Y: Between -1045 and 2250
    The code should look like this:
    Code:
    tEnem.x= //random between -30 and 1580
    tEnem.y= //random between -1045 and 2250
    I've been Googling and attempting for two hours, and I'm getting frustrated. Could any experienced programmers point me in the right direction? Thanks in advance.

  2. #2
    Senior Member Steven FN's Avatar
    Join Date
    Mar 2010
    Location
    CA, USA
    Posts
    276
    Try below, Math.random gets number between 0 and 1, so if you use it like Math.random()*3, it will return 0,1,2. In the first example, it gets numbers 0-1580, then we subtract 30 to make the minimum value -30 and highest value 1580. I think that explanation is correct. I rarely use Math.random with such large numbers in my applications, so my experience is limited in that respect.

    var randomNum:int = Math.random()*(1581+30)-30; // Integer, whole numbers, no decimals
    var randomNum:Number = Math.random()*(2251+1045)-1045; // Number with trailing decimals

    Use either int or Number, depending on what you want, i would use int for whole numbers.

  3. #3
    Junior Member
    Join Date
    Sep 2012
    Posts
    9
    I have no idea what I'm doing... I have it like this:
    Code:
    tEnem.x= Math.random()*(2250+310)-310;
        tEnem.y= Math.random()*(1581+30)-30;
    The enemies spawn in the exact x y position each time.

    Edit: *facepalm* I forgot the underscore in the x, y position. To anyone else who needs help with this:
    Code:
    tEnem._x= Math.random()*(2250+310)-310;
        tEnem._y= Math.random()*(1581+30)-30;
    Attached Images Attached Images
    Last edited by Beocro; 09-21-2012 at 06:46 AM.

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  




Click Here to Expand Forum to Full Width

HTML5 Development Center