Creating Random X and Y Functions in Phaser3

Here’s how to create and use two convenient rY() and rX() functions that an be used to replace x and y anywhere with a value that is random for the current game. There are other ways to do this built into Phaser3 but this method works with any JavaScript anywhere.

Step by Step

Because these are universal they can go at the very top of your file outside of any class or other enclosing block.

Here are the finished functions, but make sure you understand what they do and why they work:

const rX = () => Math.floor(Math.random() * game.config.width)
const rY = () => Math.floor(Math.random() * game.config.height)

Now you can use them.

  this.image.create(rx(), ry(), 'tree')

You can also use the boolean or || operator to allow a random value to be the default if no other value is provided:

const placeHappyTree = (x,y) => {
  this.image.create( x||rX(), y||rY(), 'tree')

⚠️ This won’t work if you ever want to use a 0 for x or y.