Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //http://youtube.com/user/thecplusplusguy
- //move rect on vector
- #include <iostream>
- #include <SDL/SDL.h>
- #include <cmath>
- void calculateVector(float sx,float sy,float ex,float ey,float& vecx,float& vecy)
- {
- //a direction vector: end_point-start_point
- vecx=ex-sx;
- vecy=ey-sy;
- //calculate the length with the help of pythagorean theorem
- float length=sqrt(vecx*vecx+vecy*vecy); //might be std::sqrt
- if(length!=0.0)
- {
- //and normalize the vector
- vecx/=length;
- vecy/=length;
- }
- }
- int main(int argc,char** argv)
- {
- float curX=30,curY=40; //The current position of the rect. I use float, so we don't loose precision, for example imagine
- //if the speed is 0.5 So I add do curX+=0.5 which is just curX, because it casted to an int, with float, we don't have such a problem.
- int endX=30,endY=40; //this can stay an int, because this is just the end coordinate
- float vecx=0.0,vecy=0.0; //The vector, because it will be between 0.0 and 1.0, definitely have to be a float, this is the 2 separate
- //component of a 2D vector, if you want to use vectors often, create a class for them
- float speed=3.0; //3 pixel/s
- calculateVector(curX,curY,endX,endY,vecx,vecy); //calculate the direction vector
- SDL_Surface* screen=SDL_SetVideoMode(640,480,32,SDL_SWSURFACE);
- SDL_Event event;
- Uint32 start;
- bool running=true;
- while(running)
- {
- start=SDL_GetTicks();
- while(SDL_PollEvent(&event))
- {
- if(event.type==SDL_QUIT)
- running=false;
- else if(event.type==SDL_MOUSEBUTTONDOWN)
- {
- //if we clicked somewhere, calculate the new direction vector with the new end coordinate
- endX=event.button.x;
- endY=event.button.y;
- calculateVector(curX,curY,endX,endY,vecx,vecy);
- }
- }
- //if we are close enough, just place make the current coordinate to the end coordinate (so we don't have to add lengthed vectors)
- if(abs(curX-(float)endX)<5 && abs(curY-(float)endY)<5) //might be std::abs
- {
- curX=endX;
- curY=endY;
- }else{
- //else do the vector operation, and move on that direction
- curX+=speed*vecx;
- curY+=speed*vecy;
- }
- SDL_Rect rec;
- rec.x=curX;
- rec.y=curY;
- rec.w=20;
- rec.h=20;
- SDL_FillRect(screen,0,0); //clear screen
- SDL_FillRect(screen,&rec,SDL_MapRGB(screen->format,255,0,0)); //draw the rect on the screen
- SDL_Flip(screen);
- if(1000.0/30.0>(SDL_GetTicks()-start))
- SDL_Delay(1000.0/30.0-(SDL_GetTicks()-start));
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement