Math.random acting different with sprites?

Hi, so I am trying to make a button appear on a random chance using this.

    var disableRateButton = function() {
        var rnd = Math.random();
        var item = app.root.findByName('Rate Button');

        if (rnd > 0.8) {
            item.enabled = true;
        else {
            item.enabled = false;

And of course, where it was necessary, I put disableRateButton(); (when I went back to the menu). This used to work when the game used models and stuff to make it 2D, but with the implementation of sprites, this doesn’t work anymore. Any help is greatly appreciated.

Hi @ThePastaNebula and welcome!

So Math.random() will return a random number between 0.0 - 1.0, shouldn’t have any different output no matter where or with what you are using it.

I imagine the issue is somewhere else, you can of course debug that code and check what is the value of rnd each time.

If you don’t manage to find the cause, try posting a project url to take a look.

Replace this line with:

var item ='Rate Button');

I found this easier to do using Math.ceil(Math.random() * 3), since I wanted a 1/3 chance of it showing. From there it was very simple,'rate:chance', function () {

var rnd = Math.ceil(Math.random() * 3);
this.item ='Rate Button');

if (rnd > 0 && rnd <= 1) {
    var pos;
    pos = this.item.getPosition();
    this.item.setPosition(100, 100, 0);

if (rnd > 1 && rnd <= 2) {
    var pos2;
    pos2 = this.item.getPosition();

    // original location
    this.item.setPosition(0.31, -0.395, 0);

if (rnd > 2 && rnd <= 3) {
    var pos2;
    pos2 = this.item.getPosition();
    this.item.setPosition(100, 100, 100);
}, this);'rate:chance');

I probably made it harder than it needed to be, but nevertheless, it worked. :slightly_smiling_face:


Hi @ThePastaNebula, nice work!

And thanks for sharing your solution.

1 Like