Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //http://www.youtube.com/user/thecplusplusguy
- #include <SDL/SDL.h>
- #include <iostream>
- //put a pixel to the screen
- void putPixel(int x,int y)
- {
- if(x<0 || x>640 || y<0 || y>480)
- return;
- Uint32* pixels=(Uint32*)SDL_GetVideoSurface()->pixels;
- Uint32* pixel=pixels+y*SDL_GetVideoSurface()->pitch/4+x;
- *pixel=SDL_MapRGB(SDL_GetVideoSurface()->format,0xff,0xff,0xff);
- }
- //get the absolute value of a number (the abs() works only for ints I think
- double absolut(double d)
- {
- return (d>0 ? d : -d);
- }
- //draw a line
- void drawline(SDL_Surface* screen,int x1,int y1,int x2,int y2)
- {
- if(x2>x1)
- {
- int x=x1,y=y1;
- double deltaerr=(float)(y2-y1)/(x2-x1);
- double error=0.0;
- while(x<x2)
- {
- putPixel(x,y);
- error+=deltaerr;
- if(error>=0.5)
- {
- y++;
- error-=1.;
- }
- x++;
- }
- }else if(x1>x2)
- {
- int x=x1,y=y1;
- double deltaerr=absolut((double)(y2-y1)/(x2-x1));
- double error=0.0;
- while(x>x2)
- {
- putPixel(x,y);
- error+=deltaerr;
- if(error>=0.5)
- {
- y++;
- error-=1.;
- }
- x--;
- }
- }else if(x1==x2)
- {
- for(int i=y1;i<y2;i++)
- {
- putPixel(x1,i);
- }
- }else if(y1>y2)
- {
- }
- }
- //check collision between the ray and the line
- bool lineray(float xs,float ys,float xd,float yd,int x1,int y1,int x2,int y2)
- {
- float t=t = (xs*(y2 - y1) + ys*(x1 - x2) + y1*x2 - y2*x1)/(yd*x2 - x1 *yd - y2*xd + y1*xd);
- if(t<0)
- return false;
- int x=xs+t*xd;
- int y=ys+t*yd;
- if(x>=x1 && x<=x2 && y>=y1 && y<=y2)
- {
- drawline(SDL_GetVideoSurface(),x,y,x,y+100);
- return 1;
- }
- return 0;
- }
- int main(int argc,char** argv)
- {
- SDL_Init(SDL_INIT_EVERYTHING);
- SDL_Surface* screen=SDL_SetVideoMode(640,480,32,SDL_SWSURFACE);
- bool running=true;
- SDL_Event event;
- Uint32 start;
- bool b[4]={0,0,0,0};
- int x=100,y=100;
- while(running)
- {
- start=SDL_GetTicks();
- while(SDL_PollEvent(&event))
- {
- switch(event.type)
- {
- case SDL_QUIT:
- running=false;
- break;
- case SDL_KEYDOWN:
- switch(event.key.keysym.sym)
- {
- case SDLK_UP:
- b[0]=true;
- break;
- case SDLK_LEFT:
- b[1]=true;
- break;
- case SDLK_DOWN:
- b[2]=true;
- break;
- case SDLK_RIGHT:
- b[3]=true;
- break;
- }
- break;
- case SDL_KEYUP:
- switch(event.key.keysym.sym)
- {
- case SDLK_UP:
- b[0]=false;
- break;
- case SDLK_LEFT:
- b[1]=false;
- break;
- case SDLK_DOWN:
- b[2]=false;
- break;
- case SDLK_RIGHT:
- b[3]=false;
- break;
- }
- break;
- }
- }
- //render
- if(b[0])
- y--;
- if(b[1])
- x--;
- if(b[2])
- y++;
- if(b[3])
- x++;
- SDL_FillRect(screen,&screen->clip_rect,SDL_MapRGB(screen->format,0,0,0));
- putPixel(50,50);
- drawline(screen,10,10,200,100);
- drawline(screen,x,y,x+0.70710*100,y+0.70710*100);
- lineray(x,y,0.70710,0.70710,10,10,200,100);
- SDL_Flip(screen);
- if(1000/30>(SDL_GetTicks()-start))
- SDL_Delay(1000/30-(SDL_GetTicks()-start));
- }
- SDL_Quit();
- }
Advertisement
Add Comment
Please, Sign In to add comment