How do I randomly respawn correctly

0 favourites
  • 5 posts
  • So I've been having problems with respawning am object. I designed a simple game where there is a square and when you click on it you gain 1 point. When you click on it the object respawns to a random location (which is what I wanted).

    I did this by doing the following

    'Set position'

    X axis....random (950)

    Y axis....random (450)

    Since the screen has been set to 1280 x 715 it gives plenty of excess space so that the square does not go of the screen. The cube is 90x90.

    So the problem is that when it respawns it occasionally goes half off the screen so only half of the cube is visible on the screen even when u set the randon position to 'x axis random (200)' and 'y axis random (100)' it still spawns partly off the screen. Any ideas????

    Thanks so much

  • Try Construct 3

    Develop games in your browser. Powerful, performant & highly capable.

    Try Now Construct 3 users don't see these ads
  • random(950) means you'll have a number 0..949

    if your X coordinate will become from 0 to 45 (your square width/2) you'll see square partly off the screen. Right?

    I suppose that your square origin point is in its center.

    You must spawn X in range: from (square.width/2) to (screen.width - square.width/2)

    Use this:

    random(m - n + 1) + n,

    where m - higher bound, n - lower bound

    Let's take our example: m = 1280 - 45 = 1235, n = 90/2 = 45

    random(1235 - 45 + 1) + 45 = random(1191) + 45

    The lower bound is 0 + 45 = 45

    The higher bound is 1190 + 45 = 1235

    Make so on with Y coordinate.

    Also don't forget, if you want normal integer coordinates (not float) you must write your random this way:

    floor(random()). In this way full expression will be: floor(random(m - n + 1)) + n

  • Thanks so much it worked.! Im not very gpod woth programming language what did the integer float part mean. I know an integer is a number thats about it

    Thanks again

  • integer numbers are: 1, 50, 437, 189000 etc.

    float numbers are: 1.5, 0.125, 46.333 etc.

    see the difference?

    javascript by default makes float random - number from 0 to 1

    c2 improves it in this way: if you write for example random(47) it will return an integer part from 0 to 46 plus float part from 0 to 1 (as example, 35.005463528755)

    we need floor function to eliminate this float part (floor function rounds float number down, for example floor(55.001) = 55 and floor(55.999) = 55 too)

    so floor(random(47)) will return just integer numbers from 0 to 46 (0, 1, 2, 3, ..., 45, 46)

    of course, using floor function is optionally

    Does my explanation clear?

  • thanks so much

Jump to:
Active Users
There are 1 visitors browsing this topic (0 users and 1 guests)