Hey I am currently trying to create a brickbreaker game and struggling to find a way to get the ball to bounce off the walls, panel, and bricks. Any help would be appreciated. This is my current code: import greenfoot.*;
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 85 86 87 88 89 90 91 92 93 94 95 96 97 98 | import greenfoot.*; /** * Write a description of class Ball here. * * @author (your name) * @version (a version number or a date) */ public class Ball extends Actor{ private int ballX; private int ballY; private int oldEdge; private int vel; /** * Move the ball. Then check what we've hit. */ public void act() { move( 5 ); setRotation( 180 ); } public void move() { setLocation (getX() + ballX, getY() + ballY); checkWalls(); checkBlock(); } public void checkWalls() //public int atWorldEdge() boolean atXEdge = getX() < 10 || getX() > getWorld().getWidth()- 10 ; boolean atYEdge = getY() < 10 || getY() > getWorld().getHeight()- 10 ; if (atXEdge || atYEdge) move(- 5 ); if (atYEdge) setRotation( 360 -getRotation()); if (atXEdge) setRotation( 540 -getRotation()); } public void turnAtFloor() { if (getY() + getImage().getHeight()/ 2 >=getWorld().getHeight() ) { vel.reverseY(); } } public void turnAtRightWall() { if (getX() + getImage().getWidth()/ 2 >=getWorld().getWidth() ) { vel.reverseX(); } } public void turnAtRoof() { if (getY() + getImage().getHeight()/ 2 <=getWorld().getHeight() ) { vel.reverseY(); } } public void turnAtLeftWall() { if (getX() + getImage().getWidth()/ 2 <=getWorld().getWidth() ) { vel.reverseX(); } } /** * Check whether we're out (bottom of screen).If not out at bottom * then check if we have completed the level. */ public void checkBlock() { Actor brick = getOneIntersectingObject(Bricks. class ); if (brick != null ) { ballY = -ballY; } } //End of Borrowed public void move( int dist) { setLocation (getX() + dist, getY()); } public void release() { ballX = Greenfoot.getRandomNumber( 11 ) - 5 ; ballY = - 5 ; } } |