Skip to content Skip to sidebar Skip to footer

What Is Going On With This Function?

Code: this.moveLeft = function(speed) { speed *= -1; // Make speed a negative number this.move( speed, 0 ); }; this.moveUp = function(speed) { speed

Solution 1:

If I am not wrong there are 4 functions here and everyone with a parameter.

Correct, except move takes two parameters (arguments).

Why move left and up is a negative number?

Because in browsers, the coordinates on the page start at 0,0 in the left,top of the page, the x increases as you move right, and the y increases as you move down. So to move "left" you reduce the x coordinate, and to move "up" you reduce the y coordinate.

And also, why zero (0) changes its position with the parameter "speed" when there is moving left and moving up?

Because there are two coordinates, x (horizontal) and y (vertical). moveLeft moves left (reduces the horizontal, without changing the vertical, so the vertical is 0). moveUp moves up (reduces the vertical without changing the horizontal, so the horizontal is 0).

Solution 2:

Why move left and up is a negative number?

Because the game works on an "inverted-grid":

HTML canvas grid

So while your intuition would say that UP is positive, it is in fact negative on this grid system. Left is always negative, i.e. if you are in (3, 0) and you move one unit left, you end up in (3 - 1, 0) = (2, 0).

And also, why zero (0) changes its position with the parameter "speed" when there is moving left and moving up?

I am not sure about what you mean here but the speed is the number of units you move in a certain interval of time. In my example about (3, 0) => (2, 0), the speed is "1" (you move one unit).

Hope that makes sense.

Solution 3:

My guess is that this.move takes two arguments:

  1. The first one is the amount to be moved towards right
  2. The second one is the amount to be moved towards bottom

Then,

  • this.moveLeft moves -speed units towards right (i.e speed units towards left), and 0 units towards bottom.
  • this.moveUp moves 0 units towards right, and -speed units towards bottom (i.e speed units towards top).
  • this.moveDown moves 0 units towards right, and speed units towards bottom (i.e speed units towards top).

Why move left and up is a negative number

Because multiplying a vector by -1, you get a vector of the same length but opposite direction.

Why zero (0) changes its position with the parameter "speed" when there is moving left and moving up?

Because this way the scalar product of the vectors gives always 0, that is, they are perpendicular.

Solution 4:

The speed integer corresponds to the movement of the "character". So if 1 is north then -1 would be south.

So when passed into the move() function which has an x and y parameter:

move(-1, 0) Would move left

move(1, 0) Would move right

move(0, -1) Would move south

move(0, 1) Would move north

Post a Comment for "What Is Going On With This Function?"