I'm trying to get the ball movement (angular/velocity changes upon collision) in a breakout type game working. It would seem that this should be an easy problem not requiring any fancy physics but I can't seem to get it right. Could someone either post a bit of code from their breakout game or read the following and help me get it right?
Specifically I am having problems with the ball not coming off of a collsion with a block in the correct manner so I end up with weird ball movement. This movement can cause a single horizontal row to be cleared by the ball becuase it never deflects enough to get outside of the row.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
| public void update(long currentTime) { super.update(currentTime); if(!lockedToPaddle) { if(posX<20) { posX=20; setXVelocity(-getXVelocity()); } else if((posX+width)>(m.displayWidth-20)) { posX=(m.displayWidth-20)-width; setXVelocity(-getXVelocity()); }
if(posY<=40) { posY=40; setYVelocity(-getYVelocity()); } else if((posY+height)>m.displayHeight) { posY=(m.displayHeight-20)-height; lockedToPaddle=true; } else { if(hasCollided(m.player)) { setYVelocity(-getYVelocity()); float val = (getX()-m.player.getX()+getWidth())/m.player.getWidth(); if(val<.5f && getXVelocity()<0) setXVelocity(getXVelocity()-(1f*val)); else if(val<.5f && getXVelocity()>=0) setXVelocity(-getXVelocity()-(1f*val)); else setXVelocity(getXVelocity()+(1f*val)); System.out.println(""+val); } }
int pw = m.mapDisplay.cellBlock.cellPixelWidth; int ph = m.mapDisplay.cellBlock.cellPixelHeight; int startColumn = (int)((getX()-20)/(float)pw); int endColumn = (int)((getX()-20+getWidth())/(float)pw); int startRow = (int)((getY()-40)/(float)ph); int endRow = (int)((getY()-40+getHeight())/(float)ph); boolean top = false; boolean bottom = false; boolean left = false; boolean right = false;
for(int row=startRow;row<=endRow;row++) { for(int col=startColumn;col<=endColumn;col++) { MapCell cell = null;
cell = m.mapDisplay.cellBlock.getCell(col,row,0); if(cell!=null && cell.fringeIcon>=0 && !m.mapDisplay.palette.getIcon(cell.fringeIcon).isFlagSet(MapTerrainIcon.FLAG_WALKABLE)) { cell.fringeIcon = -1; m.mapDisplay.changed=true; m.soundHandler.playAudioClip(m.hitSound);
if(getYVelocity()<0 && !top) bottom=true; else if(getYVelocity()>0 && !bottom) top=true;
if(getXVelocity()<0 && (!right && !bottom && !top)) left=true; else if(getXVelocity()>0 && (!left && !bottom && !top)) right=true; } } } if(bottom || top) setYVelocity(-getYVelocity()); if(left || right) setXVelocity(-getXVelocity()); } } |