Jump to content

(SDL)Bug Num Jogo


Psilvestre
 Share

Recommended Posts

Boas,estou á um dia a tentar fazer um jogo e já tenho um bug.

O jogo é supostamente sobre fugir de zombies e tentar mata-los mas ja tenho um erro qu e quando o jogador tenta disparar a bala nao vai para onde devia.

Ta aqui o codigo:

   

#include "SDL/SDL.h"
#include "SDL/SDL_opengl.h"
#include <iostream>


bool checkCollision(float Ax, float Ay, float Aw, float Ah, float Bx, float By, float Bw, float Bh) //Funcfion for checking collision
{
  if ( Ay+Ah < By ) return false; //if A is more to the left than B
  else if ( Ay > By+Bh ) return false; //if A is more to the right than B
  else if ( Ax+Aw < Bx ) return false; //if A is higher than B
  else if ( Ax > Bx+Bw ) return false; //if A is lower than B

  return true; //There is a collision because none of above returned false
}

//start of the program
int main( int argc, char* args[] )
{
  //initialize SDL
  SDL_Init(SDL_INIT_EVERYTHING);

  //Set OpenGL memory usage
  SDL_GL_SetAttribute( SDL_GL_RED_SIZE, 8 );
  SDL_GL_SetAttribute( SDL_GL_GREEN_SIZE, 8);
  SDL_GL_SetAttribute( SDL_GL_BLUE_SIZE, 8 );
  SDL_GL_SetAttribute( SDL_GL_ALPHA_SIZE, 8);
  SDL_GL_SetAttribute( SDL_GL_BUFFER_SIZE, 32);
  SDL_GL_SetAttribute( SDL_GL_DEPTH_SIZE, 16 );
  SDL_GL_SetAttribute( SDL_GL_DOUBLEBUFFER, 1 );


  //Caption of the window
  SDL_WM_SetCaption( "ZombiesDidWhat", NULL );

  //Size of the window
  SDL_SetVideoMode(600,600,32, SDL_OPENGL );

  //Specific the clear color
  glClearColor(1,1,1,1); //RED,GREEN,BLUE,ALPHA

  //What portion of the screen we will display
  glViewport(0,0,600,600);

  //Shader model - Use this
  glShadeModel(GL_SMOOTH);

  //2D rendering
  glMatrixMode(GL_PROJECTION);

  //"Save" it
  glLoadIdentity();

  //Disable depth checking
  glDisable(GL_DEPTH_TEST);

  std::cout << "OpenGL is running\n";
  std::cout << "Main loop has started\n";

  //Handles the main loop
  bool isRunning = true;
  
  
  float feX;
  float feY;
   
  float pX;
  float pY;
  float pW=5;
  float pH=5;

  //For handling with event
  SDL_Event event;

  float myX = 300; //starting x position of player
  float myY = 535; //starting y position of player
  float width = 20; //width of the player & zombies
  float height = 65; //height of the player & zombies
  
  float z1X = 300; //starting x position of zombie
  float z1Y = 1; //starting y position of zombie
  
  float z2X = 100; //starting x position of zombie
  float z2Y = 200; //starting y position of zombie
  
  float z3X = 500; //starting x position of zombie
  float z3Y = 300; //starting y position of zombie
  


bool firing;
  bool left = false,right = false; //we save in which state the button is
  bool up = false, down = false;
  //UP DOWN MOVEMENT
  /*
  bool up = false, down = false;
  */

  //Main game loop
  while ( isRunning )
    {

      //EVENTS
      while ( SDL_PollEvent(&event) )
        {
          //if the window was closed
          if ( event.type == SDL_QUIT )
            {
              isRunning = false;
            }

          //If a button was released and the button is escape
          if ( event.type == SDL_KEYUP && event.key.keysym.sym == SDLK_ESCAPE )
            {
              isRunning = false;
            }

          if ( event.type == SDL_KEYDOWN ) //Check for presed down buttons
            {
              if ( event.key.keysym.sym == SDLK_LEFT ) //Check left key
                {
                  left = true; //Set the boolean value for left key to true (it is pressed)
                }

              else if ( event.key.keysym.sym == SDLK_RIGHT ) //Check Right key
                {
                  right = true; //Set the boolean value for right key to true (it is pressed)
                }
else if ( event.key.keysym.sym == SDLK_UP )
                {
                  up = true;
                }

              else if ( event.key.keysym.sym == SDLK_DOWN )
                {
                  down = true;
                  }

            }

          else if ( event.type == SDL_KEYUP ) //Checking for released buttons
            {
              if ( event.key.keysym.sym == SDLK_LEFT ) //Left key
                {
                  left = false; //Set the value to false (key is released)
                }
             
              else if ( event.key.keysym.sym == SDLK_RIGHT ) //Right key
                {
                  right = false; //Key is released
                }

else if ( event.key.keysym.sym == SDLK_UP )
                {
                  up = false;
                }

              else if ( event.key.keysym.sym == SDLK_DOWN )
                {
                  down = false;
                }
              
              //UP DOWN MOVEMENT
              /*
              else if ( event.key.keysym.sym == SDLK_UP )
                {
                  up = false;
                }

              else if ( event.key.keysym.sym == SDLK_DOWN )
                {
                  down = false;
                }
              */

            }

          //logic that should happen for a certain event
        }

      //LOGIC
      if ( left == true ) //If left key is pressed
        {
          myX -= 2.5; //Move left
        }

      if ( right == true ) //If right key is pressed
        {
          myX += 2.5; //Move right
        }

      if ( myX < 0 ) //If the left border of the pad is over the left part of the screen
        {
          myX = 0; //Put the pad back so it isn't over the border
        }

      if ( myX+width > 600 ) //If the pad is over the right border of the screen
        {
          myX = 600-width; //Move it back so it only touches the right border
        }

if ( up == true )
        {
          myY -= 2.5;
        }

      if ( down == true )
        {
          myY += 2.5;
        }

      if ( myY < 0 ) //Upper border of screen
        {
          myY = 0;
        }

      if ( myY + height > 600 ) //Bottom border of screen
        {
          myY = 600-height;
        }
        
        
        
        
        

if (z1X > myX)
z1X-=1;
else if (z1X < myX)
z1X+=1;
if (z1Y > myY)
z1Y-=1;
else if (z1Y < myY)
z1Y+=1;


if (z2X > myX)
z2X-=1;
else if (z2X < myX)
z2X+=1;
if (z2Y > myY)
z2Y-=1;
else if (z2Y < myY)
z2Y+=1;

if (z3X > myX)
z3X-=1;
else if (z3X < myX)
z3X+=1;
if (z3Y > myY)
z3Y-=1;
else if (z3Y < myY)
z3Y+=1;

if ( checkCollision(z1X,z1Y,width,height,myX,myY,width,height) == true ) //if there is a collision between the ball and pad
        {
          isRunning = false;
        }
if ( checkCollision(z2X,z2Y,width,height,myX,myY,width,height) == true ) //if there is a collision between the ball and pad
        {
          isRunning = false;
        }
if ( checkCollision(z3X,z3Y,width,height,myX,myY,width,height) == true ) //if there is a collision between the ball and pad
        {
          isRunning = false;
        }
       
if ( checkCollision(z1X,z1Y,width,height,z2X,z2Y,width,height) == true ) //if there is a collision between the ball and pad
        {
         z1X+=0.7;
         z1Y+=0.7; 
        }       
if ( checkCollision(z3X,z3Y,width,height,z2X,z2Y,width,height) == true ) //if there is a collision between the ball and pad
        {
         z2X+=0.7;
         z2Y+=0.7;          
        }         
if ( checkCollision(z1X,z1Y,width,height,z3X,z3Y,width,height) == true ) //if there is a collision between the ball and pad
        {
         z1X+=0.7;
         z1Y+=0.7;  
        }         
       
       
       
    //If a mouse button was pressed
    if( event.type == SDL_MOUSEBUTTONDOWN)
    {
        //If the left mouse button was pressed
        if( event.button.button == SDL_BUTTON_LEFT )
        {
            //Get the mouse offsets
            feX=event.button.x;
            feY=event.button.y;
            
            pX=myX;
            pY=myY;

firing = true;            
if (pX > feX)
pX-=20;
else if (pX < feX)
pX+=20;
if (pY > feY)
pY-=20;
else if (pY < feY)
pY+=20;
    
    if(firing == true && pX == feX && pY == feY)
              firing = false;
            
            }
        }
          
    if( event.type == SDL_MOUSEBUTTONUP)
    {
        //If the left mouse button was pressed
        if( event.button.button == SDL_BUTTON_LEFT )
        {
firing = false;
            
            }
        }   
       
       
      //UP DOWN MOVEMENT
      /*
      if ( up == true )
        {
          myY -= 0.3;
        }

      if ( down == true )
        {
          myY += 0.3;
        }

      if ( myY < 0 ) //Upper border of screen
        {
          myY = 0;
        }

      if ( myY + height > 400 ) //Bottom border of screen
        {
          myY = 400-height;
        }
      */

      //RENDERING to the screen
      glClear(GL_COLOR_BUFFER_BIT);

      glPushMatrix(); //Start rendering phase

      glOrtho(0,600,600,0,-1,1); //Set the matrix

      glColor4ub(0,0,255,255); 

      glBegin(GL_QUADS); //Start drawing the rectangle

      glVertex2f(myX,myY); //Upper-left corner
      glVertex2f(myX+width,myY); //Upper-right corner
      glVertex2f(myX+width,myY+height); //Down-right corner
      glVertex2f(myX,myY+height); //Down-left corner

      glEnd(); //End drawing
      
      glColor4ub(0,220,35,255); 

      glBegin(GL_QUADS); //Start drawing the rectangle

      glVertex2f(z1X,z1Y); //Upper-left corner
      glVertex2f(z1X+width,z1Y); //Upper-right corner
      glVertex2f(z1X+width,z1Y+height); //Down-right corner
      glVertex2f(z1X,z1Y+height); //Down-left corner

      glEnd(); //End drawing
      
      glBegin(GL_QUADS); //Start drawing the rectangle

      glVertex2f(z2X,z2Y); //Upper-left corner
      glVertex2f(z2X+width,z2Y); //Upper-right corner
      glVertex2f(z2X+width,z2Y+height); //Down-right corner
      glVertex2f(z2X,z2Y+height); //Down-left corner

      glEnd(); //End drawing
      
      glBegin(GL_QUADS); //Start drawing the rectangle

      glVertex2f(z3X,z3Y); //Upper-left corner
      glVertex2f(z3X+width,z3Y); //Upper-right corner
      glVertex2f(z3X+width,z3Y+height); //Down-right corner
      glVertex2f(z3X,z3Y+height); //Down-left corner

      glEnd(); //End drawing
          
      if (firing == true)
      {
            glColor4ub(125,125,125,255); 

      glBegin(GL_QUADS); //Start drawing the rectangle

      glVertex2f(pX,pY); //Upper-left corner
      glVertex2f(pX+pW,pY); //Upper-right corner
      glVertex2f(pX+pW,pY+pH); //Down-right corner
      glVertex2f(pX,pY+pH); //Down-left corner

      glEnd(); //End drawing           
      }    
          
          
      
      glPopMatrix(); //End rendering phase

      SDL_GL_SwapBuffers();

      SDL_Delay(1); //Delay / pause
    }

  SDL_Quit();

  return 0;
}

Se precisarem de mais detalhes digam, admito que o codigo esta confuso.

Link to comment
Share on other sites

Tira a actualização da posição da bala de dentro do evento e mete-a dentro do "if (firing == true)".

Edit

Outras coisitas:

1) porquê float? Eu costumo dizer "sem uma razão forte para não usar double, usa sempre double". O compilador, provavelmente, antes de fazer cálculos com os valores vai convertê-los para double ... e no fim dos cálculos converte para float! Um valor com ponto decimal no código é um double.

2) faz um array para os zombies

What have you tried?

Não respondo a dúvidas por PM

A minha bola de cristal está para compor; deve ficar pronta para a semana.

Torna os teus tópicos mais atractivos e legíveis usando a tag CODE para colorir o código!

Link to comment
Share on other sites

Quanto ao array de zombies, eu estava antes a pensar fazer uma structure

Então faz um array de structures :-)

Ou classes, uma vez que estás a programar em C++.

Quanto ao programa e à gestão da bala ... preciso de compilar e executar o programa e, aqui no trabalho, não tenho o SDL disponível. Se não tiveres resposta antes disso, logo à noite tento ver o que se passa.

What have you tried?

Não respondo a dúvidas por PM

A minha bola de cristal está para compor; deve ficar pronta para a semana.

Torna os teus tópicos mais atractivos e legíveis usando a tag CODE para colorir o código!

Link to comment
Share on other sites

Ok obrigado por ajudares mas eu mudei mais umas coisinhas nas balas.

Basicamente troquei o mouse down para mouse up.

Aqui esta o codigo novo:

#include "SDL/SDL.h"
#include "SDL/SDL_opengl.h"
#include <iostream>


bool checkCollision(float Ax, float Ay, float Aw, float Ah, float Bx, float By, float Bw, float Bh) //Funcfion for checking collision
{
  if ( Ay+Ah < By ) return false; //if A is more to the left than B
  else if ( Ay > By+Bh ) return false; //if A is more to the right than B
  else if ( Ax+Aw < Bx ) return false; //if A is higher than B
  else if ( Ax > Bx+Bw ) return false; //if A is lower than B

  return true; //There is a collision because none of above returned false
}

//start of the program
int main( int argc, char* args[] )
{
  //initialize SDL
  SDL_Init(SDL_INIT_EVERYTHING);

  //Set OpenGL memory usage
  SDL_GL_SetAttribute( SDL_GL_RED_SIZE, 8 );
  SDL_GL_SetAttribute( SDL_GL_GREEN_SIZE, 8);
  SDL_GL_SetAttribute( SDL_GL_BLUE_SIZE, 8 );
  SDL_GL_SetAttribute( SDL_GL_ALPHA_SIZE, 8);
  SDL_GL_SetAttribute( SDL_GL_BUFFER_SIZE, 32);
  SDL_GL_SetAttribute( SDL_GL_DEPTH_SIZE, 16 );
  SDL_GL_SetAttribute( SDL_GL_DOUBLEBUFFER, 1 );


  //Caption of the window
  SDL_WM_SetCaption( "ZombiesDidWhat", NULL );

  //Size of the window
  SDL_SetVideoMode(600,600,32, SDL_OPENGL );

  //Specific the clear color
  glClearColor(1,1,1,1); //RED,GREEN,BLUE,ALPHA

  //What portion of the screen we will display
  glViewport(0,0,600,600);

  //Shader model - Use this
  glShadeModel(GL_SMOOTH);

  //2D rendering
  glMatrixMode(GL_PROJECTION);

  //"Save" it
  glLoadIdentity();

  //Disable depth checking
  glDisable(GL_DEPTH_TEST);

  std::cout << "OpenGL is running\n";
  std::cout << "Main loop has started\n";

  //Handles the main loop
  bool isRunning = true;
  
  
  float feX;
  float feY;
   
  float pX;
  float pY;
  float pW=5;
  float pH=5;

  //For handling with event
  SDL_Event event;

  float myX = 300; //starting x position of player
  float myY = 535; //starting y position of player
  float width = 20; //width of the player & zombies
  float height = 65; //height of the player & zombies
  
  float z1X = 300; //starting x position of zombie
  float z1Y = 1; //starting y position of zombie
  
  float z2X = 100; //starting x position of zombie
  float z2Y = 200; //starting y position of zombie
  
  float z3X = 500; //starting x position of zombie
  float z3Y = 300; //starting y position of zombie
  


bool firing;
  bool left = false,right = false; //we save in which state the button is
  bool up = false, down = false;
  //UP DOWN MOVEMENT
  /*
  bool up = false, down = false;
  */

  //Main game loop
  while ( isRunning )
    {

      //EVENTS
      while ( SDL_PollEvent(&event) )
        {
          //if the window was closed
          if ( event.type == SDL_QUIT )
            {
              isRunning = false;
            }

          //If a button was released and the button is escape
          if ( event.type == SDL_KEYUP && event.key.keysym.sym == SDLK_ESCAPE )
            {
              isRunning = false;
            }

          if ( event.type == SDL_KEYDOWN ) //Check for presed down buttons
            {
              if ( event.key.keysym.sym == SDLK_LEFT ) //Check left key
                {
                  left = true; //Set the boolean value for left key to true (it is pressed)
                }

              else if ( event.key.keysym.sym == SDLK_RIGHT ) //Check Right key
                {
                  right = true; //Set the boolean value for right key to true (it is pressed)
                }
else if ( event.key.keysym.sym == SDLK_UP )
                {
                  up = true;
                }

              else if ( event.key.keysym.sym == SDLK_DOWN )
                {
                  down = true;
                  }

            }

          else if ( event.type == SDL_KEYUP ) //Checking for released buttons
            {
              if ( event.key.keysym.sym == SDLK_LEFT ) //Left key
                {
                  left = false; //Set the value to false (key is released)
                }
             
              else if ( event.key.keysym.sym == SDLK_RIGHT ) //Right key
                {
                  right = false; //Key is released
                }

else if ( event.key.keysym.sym == SDLK_UP )
                {
                  up = false;
                }

              else if ( event.key.keysym.sym == SDLK_DOWN )
                {
                  down = false;
                }
              
              //UP DOWN MOVEMENT
              /*
              else if ( event.key.keysym.sym == SDLK_UP )
                {
                  up = false;
                }

              else if ( event.key.keysym.sym == SDLK_DOWN )
                {
                  down = false;
                }
              */

            }

          //logic that should happen for a certain event
        }

      //LOGIC
      if ( left == true ) //If left key is pressed
        {
          myX -= 2.5; //Move left
        }

      if ( right == true ) //If right key is pressed
        {
          myX += 2.5; //Move right
        }

      if ( myX < 0 ) //If the left border of the pad is over the left part of the screen
        {
          myX = 0; //Put the pad back so it isn't over the border
        }

      if ( myX+width > 600 ) //If the pad is over the right border of the screen
        {
          myX = 600-width; //Move it back so it only touches the right border
        }

if ( up == true )
        {
          myY -= 2.5;
        }

      if ( down == true )
        {
          myY += 2.5;
        }

      if ( myY < 0 ) //Upper border of screen
        {
          myY = 0;
        }

      if ( myY + height > 600 ) //Bottom border of screen
        {
          myY = 600-height;
        }
        
        
        
        
        

if (z1X > myX)
z1X-=1;
else if (z1X < myX)
z1X+=1;
if (z1Y > myY)
z1Y-=1;
else if (z1Y < myY)
z1Y+=1;


if (z2X > myX)
z2X-=1;
else if (z2X < myX)
z2X+=1;
if (z2Y > myY)
z2Y-=1;
else if (z2Y < myY)
z2Y+=1;

if (z3X > myX)
z3X-=1;
else if (z3X < myX)
z3X+=1;
if (z3Y > myY)
z3Y-=1;
else if (z3Y < myY)
z3Y+=1;

if ( checkCollision(z1X,z1Y,width,height,myX,myY,width,height) == true ) //if there is a collision between the ball and pad
        {
          isRunning = false;
        }
if ( checkCollision(z2X,z2Y,width,height,myX,myY,width,height) == true ) //if there is a collision between the ball and pad
        {
          isRunning = false;
        }
if ( checkCollision(z3X,z3Y,width,height,myX,myY,width,height) == true ) //if there is a collision between the ball and pad
        {
          isRunning = false;
        }
       
if ( checkCollision(z1X,z1Y,width,height,z2X,z2Y,width,height) == true ) //if there is a collision between the ball and pad
        {
         z1X+=0.7;
         z1Y+=0.7; 
        }       
if ( checkCollision(z3X,z3Y,width,height,z2X,z2Y,width,height) == true ) //if there is a collision between the ball and pad
        {
         z2X+=0.7;
         z2Y+=0.7;          
        }         
if ( checkCollision(z1X,z1Y,width,height,z3X,z3Y,width,height) == true ) //if there is a collision between the ball and pad
        {
         z1X+=0.7;
         z1Y+=0.7;  
        }         
       
       
       
    //If a mouse button was pressed
    if( event.type == SDL_MOUSEBUTTONUP)
    {
        //If the left mouse button was pressed
        if( event.button.button == SDL_BUTTON_LEFT )
        {
            //Get the mouse offsets
            feX=event.button.x;
            feY=event.button.y;
            
            pX=myX;
            pY=myY;
          firing = true;
          }
}
    

  
       
      //UP DOWN MOVEMENT
      /*
      if ( up == true )
        {
          myY -= 0.3;
        }

      if ( down == true )
        {
          myY += 0.3;
        }

      if ( myY < 0 ) //Upper border of screen
        {
          myY = 0;
        }

      if ( myY + height > 400 ) //Bottom border of screen
        {
          myY = 400-height;
        }
      */

      //RENDERING to the screen
      glClear(GL_COLOR_BUFFER_BIT);

      glPushMatrix(); //Start rendering phase

      glOrtho(0,600,600,0,-1,1); //Set the matrix

      glColor4ub(0,0,255,255); 

      glBegin(GL_QUADS); //Start drawing the rectangle

      glVertex2f(myX,myY); //Upper-left corner
      glVertex2f(myX+width,myY); //Upper-right corner
      glVertex2f(myX+width,myY+height); //Down-right corner
      glVertex2f(myX,myY+height); //Down-left corner

      glEnd(); //End drawing
      
      glColor4ub(0,220,35,255); 

      glBegin(GL_QUADS); //Start drawing the rectangle

      glVertex2f(z1X,z1Y); //Upper-left corner
      glVertex2f(z1X+width,z1Y); //Upper-right corner
      glVertex2f(z1X+width,z1Y+height); //Down-right corner
      glVertex2f(z1X,z1Y+height); //Down-left corner

      glEnd(); //End drawing
      
      glBegin(GL_QUADS); //Start drawing the rectangle

      glVertex2f(z2X,z2Y); //Upper-left corner
      glVertex2f(z2X+width,z2Y); //Upper-right corner
      glVertex2f(z2X+width,z2Y+height); //Down-right corner
      glVertex2f(z2X,z2Y+height); //Down-left corner

      glEnd(); //End drawing
      
      glBegin(GL_QUADS); //Start drawing the rectangle

      glVertex2f(z3X,z3Y); //Upper-left corner
      glVertex2f(z3X+width,z3Y); //Upper-right corner
      glVertex2f(z3X+width,z3Y+height); //Down-right corner
      glVertex2f(z3X,z3Y+height); //Down-left corner

      glEnd(); //End drawing
          
      if (firing == true)
      {
                 
      if (pX > feX)
pX-=10;
else if (pX < feX)
pX+=10;
if (pY > feY)
pY-=10;
else if (pY < feY)
pY+=10;           
      
            glColor4ub(125,125,125,255); 

      glBegin(GL_QUADS); //Start drawing the rectangle

      glVertex2f(pX,pY); //Upper-left corner
      glVertex2f(pX+pW,pY); //Upper-right corner
      glVertex2f(pX+pW,pY+pH); //Down-right corner
      glVertex2f(pX,pY+pH); //Down-left corner

      glEnd(); //End drawing           
      }    
          
          
      
      glPopMatrix(); //End rendering phase

      SDL_GL_SwapBuffers();

      SDL_Delay(1); //Delay / pause
    }

  SDL_Quit();

  return 0;
}


Link to comment
Share on other sites

Afinal não tenho o meu computador de casa em condições de fazer programas com OpenGL. Talvez durante o fim-de-semana me dê para instalar e configurar as bibliotecas.

Mas reparo que nunca desligas o "firing". A variável começa com valor indeterminado e quando há um MOUSEUP metes a true ... nuca metes a false.

What have you tried?

Não respondo a dúvidas por PM

A minha bola de cristal está para compor; deve ficar pronta para a semana.

Torna os teus tópicos mais atractivos e legíveis usando a tag CODE para colorir o código!

Link to comment
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
 Share

×
×
  • Create New...

Important Information

By using this site you accept our Terms of Use and Privacy Policy. We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.