1

I'm developing a video game using JavaScript and html Canvas and I'm trying to make it so that depending on what value:

PlayerIcon = 0;

is, the computer will draw that specific number from an array:

PlayerI = [];
PlayerI[0] = new Sprite("");
PlayerI[1] = new Sprite("");
PlayerI[2] = new Sprite("");

I don't exactly understand how undefined values work (eg .this [i]) But it should be possible with them right? I already know how to do this in JavaScript however I would like to be able to make this into only a few lines of coding (no matter how many variables I add to the array):

var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
var timer = setInterval(gameLoop,10);
var PlayerIcon = 0;
var PlayerI = [];

function gameLoop()
{
if(PlayerIcon == 0)
{
PlayerI[0].draw(ctx);
}
if(PlayerIcon == 1)
{
PlayerI[1].draw(ctx);
}
if(PlayerIcon == 2)
{
PlayerI[2].draw(ctx);
}
}

then I will assign a picture to each PlayerI variable and switch which one is being displayed with the PlayerIcon variable.

1 Answer 1

3

PlayerI[PlayerIcon].draw(ctx); should do the trick

Sign up to request clarification or add additional context in comments.

4 Comments

Wait really? I didn't know it's that easy!
I just tried it and it worked! Thanks a ton! (I kinda feel bad posting this question now because it was so easy XP)
Don't worry, we all had to learn and figure out at some point. Good luck with your game
True. Thank You!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.