[SOLVED] RandomHelper in Javascript?


#1

Hi everyone, I’ve recently started my Cocoscreator + cocos2dx-JS journey and I’ve been searching of an easy way to randomize between 2 ints and only been able to find resources on the topic for C++ in this forum.
Generate Random Int 1-60

I’m currently just using a plain text editor for coding so I don’t have advantage of intellisense (Is there even one? If anyone knows please tell me!). Anyway I have already learned about cc.random0To1() & randomMinus1To1() but I don’t think I can apply it to ints easily.

I have been trying stuff like cc.RandomHelper.random_int(1,10) to no avail. Does anyone know the actual equivalent in JS or is it a C++ only thing?


#2

You can just use JavaScript Math.random() for it. Doesn’t have to be Cocos own functions.

e.g.

function getRandom(min, max) {
  return Math.random() * (max - min) + min;
}

Math.round(getRandom(1, 2)); // to get a random 1 or 2 integer value

#3

Lol, I guess I was wrong in assuming there’ll be an equivalent for JS. I’ll be using this then. :slight_smile:

Thank you for your help!


#4

Glad to help! :slightly_smiling_face: Remember to mark the thread as “Solved” if you think it’s solved.