0
\$\begingroup\$
function randArray(arrayName) {
    arln = arrayName.length;
    arst = arrayName[Math.floor(Math.random() * arln)];
    return arst;

}


    create: function(){
        //starts physics engine
        game.physics.startSystem(Phaser.Physics.ARCADE);
        player = game.add.sprite(width/2, height/2, 'player');
        randSpawnItem = game.add.sprite(10, 10, randArray(randItem));
        randSpawnItem2 = game.add.sprite(50, 50, randArray(randItem));

So the randArray function works, and there is nothing wrong with the create. I'm using Phaser, and I'm trying to spawn items randomly (kind of like in Binding of Issac.) I forsee a problem in the future, when I'm detecting for collison, I need to know what item spawned to give the right kind of item to the player. How would I get that third attribute of randSpawnItem or randSpawnItem2, or is there another way to go at this completely? Sorry if that's a noobie question! Didn't know how to word it and didn't find it anywhere else. Thanks in advance for your time.

\$\endgroup\$
  • \$\begingroup\$ This question seems to be about programming in general, and as such is off topic for this site. A better place to find an answer would be a javascript tutorial. \$\endgroup\$ – Peter Apr 19 '17 at 20:33
  • 1
    \$\begingroup\$ @Peter the site's policy on programming questions is continuing to evolve as we figure out how to best work together as a community. Myself, I think the problem described here - spawning a random item on a map and recording not just that object's visual but also what type of item was spawned in a way that's convenient to refer to for collision checking - that sounds like something a game programmer might have better & more complete/game-suitable suggestions for than we'd expect to get from a more general programmer. \$\endgroup\$ – DMGregory Apr 22 '17 at 23:48
1
\$\begingroup\$

You absolutely can. Just change what's returned and how you interact with it.

function randArray(arrayName) {
    arln = arrayName.length;
    arst = arrayName[Math.floor(Math.random() * arln)];
    return this;
}

var someArray = [1, 2, 3, 4, 5];

var random = randArray(someArray);
document.getElementById('placeholder').textContent = 'Length: ' + random.arln + ' Random item: ' + random.arst;
<div id="placeholder">
</div>

However, if you're going to continue using Phaser you might want to look at how to extend sprites in Phaser. Creating custom objects will allow you to do most of the plumbing in a single location, and help with maintainability.

| improve this answer | |
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.