mowwwalker
mowwwalker

Reputation: 17382

What's the significance of 1/cos(x) in this code for a 3d canvas game?

I've been experimenting with HTML5 canvases lately and came across this 3d example with relatively little code behind it. I was hoping to find a good introduction to 3d rendering, but I'm having more trouble understanding the geometry behind the code than I was expecting to. I set up a JSbin and copied over the code that was used on his website to play with. I'm stuck at understanding the meaning of

deltaX=1/Math.cos(theta);

which is later used in:

    if (deltaX>0) {

        stepX = 1;
        distX = (mapX + 1 - x) * deltaX;
    }
    else {
        stepX = -1;
        distX = (x - mapX) * (deltaX*=-1);      
    }

Source

My best guess is that it's used for the relation cos(x) = adjacent/hypotenuse in a right triangle, but I don't understand where the triangle would fit in, if at all.

Upvotes: 2

Views: 172

Answers (1)

Martin R
Martin R

Reputation: 539965

If you draw a line from the origin (0, 0) with direction theta (measured from the x-axis), then

  • deltaX = 1/cos(theta) is the distance on this line until the vertical line x = 1 is met, and
  • deltaY = 1/sin(theta) is the distance on this line until the horizontal line y = 1 is met.

It is indeed a triangle relation. In the first case, the triangle has the points (0, 0), (1, 0) and the point (1, y) where the line meets the vertical line x=1.

(mapX, mapY) is a grid point with integer coordinates, and (x, y) is a point in the square [mapX, mapX+1) x [mapY, mapY+1).

distX computes the distance of the next vertical grid line in theta-direction, and distY the distance of the next horizontal grid line.

Remark: The computation fails if the direction is a multiple of π/2, i.e. the direction is exactly right, up, left, or down, because sin(theta) = 0 or cos(theta) = 0 in that case. This probably does not happen in your program, because the playerDirection starts with 0.4 and is incremented or decremented by 0.07.

Upvotes: 4

Related Questions