Reputation: 1393
Anyone see a bug in my code that stops the variable "player1Bananas" from changing? Everything else in the function works fine.
//update playerStats arguments:
//banana is a banana object
//x and y are the banana's position
//players bananas is player1Bananas or player2Bananas,
//ballPosition is "left" or "right"
updatePlayerStats: function(banana, x, y, playersBananas, ballPosition) {
playersBananas += 1;
gameController.bananasTaken += 1;
banana.x = x;
banana.y = y;
gameController.player1Score = 0;
gameController.player2Score = 0;
gameController.setUpPaddles();
gameController.setUpBall(ballPosition);
},
gameController.updatePlayerStats( gameController.Banana1, 20, gameController.canvas.height - 20 - gameController.Banana1.height,
gameController.player1Bananas, "left");
Thanks!
Upvotes: 0
Views: 80
Reputation: 3016
You're passing the value of gameController.player1bananas
as a parameter to a function.
In the function that value is assigned to local variable playersBananas
and is restricted by scope. When you make a change to it, you're no longer making a change to that variable you originally passed but instead the new variable playersBananas
.
Example: http://jsfiddle.net/GHkJ6/
To fix this, you need to pass it as an object. JavaScript won't pass it as a value, but instead the object itself.
Example: http://jsfiddle.net/F446Q/
Upvotes: 5
Reputation: 252
gameController.player1Bananas is a primitive type, so it is passed by value... not reference. This means that inside the function playerBananas no longer has any reference to player1Bananas, it is simply an integer value.
Try passing in an object instead... for example, you could have a player object with a bananaCount property. Then pass the player object into the function and increment the bananaCount property of the player object.
eg.
//update playerStats arguments:
//banana is a banana object
//x and y are the banana's position
//players bananas is player1Bananas or player2Bananas,
//ballPosition is "left" or "right"
updatePlayerStats: function(banana, x, y, player, ballPosition) {
player.bananaCount += 1;
gameController.bananasTaken += 1;
banana.x = x;
banana.y = y;
gameController.player1Score = 0;
gameController.player2Score = 0;
gameController.setUpPaddles();
gameController.setUpBall(ballPosition);
},
gameController.updatePlayerStats( gameController.Banana1, 20, gameController.canvas.height - 20 - gameController.Banana1.height,
gameController.player1, "left");
See this link for a good explanation.. http://snook.ca/archives/javascript/javascript_pass
Upvotes: 1
Reputation:
change player1Bananas
to global variable then change that same player1Bananas
inside the function
Upvotes: 0
Reputation: 5460
Because in JavaScript numbers are passed by value...
You have to pass something else than a single number, like a player state object({id:1, bananas:17} for example).
Upvotes: 2