Sign in to follow this  

Raycasting math problem

Recommended Posts

Hello, I am having a problem getting my math right. I know this because my walls look like a funhouse :) If it's ok, I will post my raycasting function. My source basically contains 3 functions, one for calculating the ray which works great. 2 raycasting which is not great and drawing which works great. By the way I am programming in C++ using the Allegro game library. GRID_SIZE is a constant int equal to 64; angle[] is pre-calculated with all the angles to cast based on the FOV
void castRays(Player & ref)
  int ray_x;
  int ray_y;
  int map_x;
  int map_y;
  // end point variables will equal to ray_x/y when the rays end 
  int end_point_x;
  int end_point_y;

  // use these to calculate grid intersections before casting
  int opposite;
  int adjacent;

  // cast rays
  for(int i=0;i<SCREEN_WIDTH;i++)
    ray_x = ref.posX;
    map_x = ref.posX / GRID_SIZE;
    map_y = ref.posY / GRID_SIZE;

    //try to find the V/H intersections
    //if ray is going right
    if((angle[i] >= 0.0f) && (angle[i] < 180.0f))
      ray_x += (map_x + 1) * GRID_SIZE;
      adjacent = ref.posX - ray_x;
      opposite = int(tan((angle[i] - 90.0f) * M_PI / 180.0f) * adjacent);
      ray_y = ref.posY + adjacent;
    // if ray is going left
    else if((angle[i] >= 180.0f) && (angle[i] <= 360.0f))
      ray_x += map_x * GRID_SIZE - 1;
      adjacent = ref.posX - ray_x;
      opposite = int(tan((angle[i] - 270.0f) * M_PI / 180.0f) * adjacent);
      ray_y = ref.posY - adjacent;

    while(map[map_x][map_y] != WALL)
      ray_x += int(GRID_SIZE * cos(angle[i] * M_PI / 180.0f));
      ray_y += int(GRID_SIZE * sin(angle[i] * M_PI / 180.0f)); 

      map_x = ray_x / GRID_SIZE;
      map_y = ray_y / GRID_SIZE;
    // end point variables equal to where ray_x, ray_y end
    end_point_x = ray_x;
    end_point_y = ray_y;

    // calculate the wall distance
    wall_distance[i] = abs((end_point_y - ref.posY) / sin(ref.facing_direction));
END_OF_FUNCTION(castRays(Player & ref));
Sorry for posting that ugly chunk of code and laughing is ok :) I will explain what I am trying to do, I'm searhing for walls by skipping 64 units at a time. But before I cast i'm trying to get my ray_x and ray_y variables to the grid intersections and I am sure this is incorrect which would explain my funhouse. Can someone correct my code or tell me what i'm doing wrong? I will very much appreciate it. Erick

Share this post

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this