Book of Defold
  • Book of Defold
  • Defold A-Z
    • What is Defold?
    • Why Defold?
    • Defold History
    • Editor Tour
    • File Formats
    • game.project
    • Defold Tips
      • Anchored GUIs
      • GUIs for Window Size
      • Pixel Art Assets
    • Lua Tips
      • Lua Tables
      • About math.random()
      • Randomly 1 or -1
      • Lua Modules
      • Global Scope
    • Running Projects
    • Bundling Projects
    • Releasing Projects
    • Command Line Tools
    • Debugging Projects
  • Dive into Defold
    • Make Games Now!
    • Avoider - Action
    • Asteroids - Action
    • Level Editor - Tool
  • Dev Tips
    • Learn Programming
    • Game Business
    • Useful Software
  • Quick Projects
    • Lasers
Powered by GitBook
On this page
  1. Defold A-Z
  2. Lua Tips

Randomly 1 or -1

PreviousAbout math.random()NextLua Modules

Last updated 6 years ago

math.random(1,2) * 2 - 3

The above code can be used to get a random value of either 1 or -1.

1 * 2 = 2 - 3 = -1

2 * 2 = 4 - 3 = 1

Getting 1 or -1 can be useful for setting a value to be randomly negative or positive when multiplied by the random value. This can be useful for example for setting a direction randomly.

https://repl.it/@pkeod/Randomly1or-1repl.it