I have a Javascript question, that might be obvious, but I just can't seem to find the solution for it, and I don't know how to solve it.
(Also, I'm still pretty new to coding)
So I'm writing a patrol function for squares in my game, and for now I started out with just making the square move one way. Later on I will make it patrol back and forth. That's why I put the move function in the draw function.
I want the move function to be reusable for several squares, but I can't seem to make a general move function work. However, I can make a move function specifically for a certain square, work.
Can anyone tell me why this works:
var square = 16;
var posX = 32;
var posY = 32;
function moveSquare() {
for (i = 0; i < 10; i++) {
posX++;
}
}
function draw() {
var redSquare = { x: posX, y: posY, w: square, h: square, color: "red" };
ctx.fillStyle = redSquare.color;
rect(redSquare.x,redSquare.y,redSquare.w,redSquare.h);
moveSquare();
}
And this doesn't:
var square = 16;
var posX = 32;
var posY = 32;
function move(pos) {
for (i = 0; i < 10; i++) {
pos++;
}
}
function draw() {
var redSquare = { x: posX, y: posY, w: square, h: square, color: "red" };
ctx.fillStyle = redSquare.color;
rect(redSquare.x,redSquare.y,redSquare.w,redSquare.h);
move(posX);
}
By the way, I defined the rect function elsewhere, but I figured it wasn't important to include.
Hope you can help
move(posX)you're passingposXby value, not by reference. Meaning a copy ofposXhas 1 added to it ten times and then the function returns, and the originalposXremains the same.