Monday, April 16, 2012

CakeDream: Collision Detection

I finally got all the problems from sprint #1 fixed and am starting to do actual coding. I just had to completely rework the framework that I used. I started to use a hybrid of openGL and QGraphicsItem/Scene. I have the background, a player moving, and the code to change rooms when triggered. The problem that has my focus is collision detection along a wall.

I've done collision detection before, but this was for objects destroying each other and balls bouncing off of walls. That was easy. The problem I face is not the actual collision detection, but how to handle it when a player moves along a wall. By offsetting the player each time they hit the wall will create a "jiggle" effect that makes it look all ugly. I'm trying to find a way to anticipate the collision and if a collision is imminent, then move the player to the wall border. This is the pseudo code that I plan to implement (part of it).

void keyPressed()
{
      if up key is pressed
             moveUp = true;
      if down key is pressed
             moveDown = true
      if left key is pressed
             moveLeft = true
      if right key is pressed
             moveRight = true
}

void keyRelease()
{
      if up key is released
             moveUp = false
      if down key is released
             moveDown = false
      if left key is released
             moveLeft = false
     if right key is released
             moveRight = false
}

void animate()
{
     if(moveUp)
              if(!canCollide("up"))
                      move(velocity,0)
              else
                      setPos(getX(), topBorder)

      if(moveDown)
              if(!canCollide("down"))
                      move(-velocity,0)
              else
                      setPos(getX(), bottomBorder)

       if(moveRight)
              if(!canCollide("right"))
                      move(0,velocity)
              else
                      setPos(rightBorder, getY())

        if(moveLeft)
              if(!canCollide("left"))
                      move(0,-velocity)
              else
                      setPos(leftBorder, getY())
}

bool canCollide(string direction)
{
       switch(direction)
              case "up":
                    if(posY() - velocity < topBorder)
                          return true;
              case "down":
                    if(posY() + velocity > bottomBorder)
                          return true;
              case "right":
                    if(posX() + velocity > rightBorder)
                          return true;
               case "left":
                    if(posX() - velocity < leftBorder)
                          return true

       return false
}

Do you think this implementation can work, or is there a better way to anticipate if collision is imminent.

No comments:

Post a Comment