Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //
- struct sHitInfo
- {
- int tx, ty; // collision tile coordinates
- float rx, ry; // intersection point
- int side; // face of the tile that was hit
- // 0[up] 1[right] 2[down] 3[left]
- };
- //
- void raycast( float x1, float y1, float x2, float y2, sHitInfo *hit )
- {
- // difference vectors
- float dx = x2-x1;
- float dy = y2-y1;
- // axis step values
- float x_step = dx / (dy + (dy==0)); // ( avoid / 0 when dy==0 )
- float y_step = dy / (dx + (dx==0)); // ( avoid / 0 when dx==0 )
- // set to something un-naturaly large when ((dx or dy) == 0)
- if ( dx == 0 ) y_step = 100000;
- if ( dy == 0 ) x_step = 100000;
- // x quantised crossing point
- float x_px = (float)( (int)x1 + (int)(dx < 0 ) );
- float x_py = - (x1-x_px) * y_step;
- x_px -= x1;
- // y quantised crossing point
- float y_py = (float)( (int)y1 + (int)(dy < 0 ) );
- float y_px = - (y1-y_py) * x_step;
- y_py -= y1;
- // integer map coords
- int ix = (int)x1;
- int iy = (int)y1;
- // span? hmm, gradient riding variables
- float x_sp =-absf( x_px );
- float y_sp =-absf( y_px );
- // start stepping
- for ( ;; )
- {
- // make a step along the x axis
- if ( (x_sp+1) < (y_sp+absf(x_step) ) )
- {
- // update integer map cell coords
- ix += signi( dx );
- // update gradient variables
- x_sp += 1;
- // update to find next crossing position
- x_px += signf( dx );
- x_py += absf( y_step ) * signf( dy );
- // have we hit a wall
- if ( isBlocked( ix, iy ) )
- {
- // tile space coordinates of hit tile
- hit->tx = ix;
- hit->ty = iy;
- // ray collision point
- hit->rx = x1+x_px;
- hit->ry = y1+x_py;
- // encode the side that was hit
- hit->side = 1 + ((dx > 0) << 1);
- break;
- }
- }
- // make a step along the y axis
- else
- {
- // update integer map cell coords
- iy += signi( dy );
- // update gradient variables
- y_sp += absf( x_step );
- // update to find next crossing position
- y_px += absf( x_step ) * signf( dx );
- y_py += signf( dy );
- // have we hit a wall
- if ( isBlocked( ix, iy ) )
- {
- // tile space coordinates of hit tile
- hit->tx = ix;
- hit->ty = iy;
- // ray collision point
- hit->rx = x1+y_px;
- hit->ry = y1+y_py;
- // encode the side that was hit
- hit->side = 0 + ((dy < 0) << 1);
- break;
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement