Hello, I've been trying to code a Pong game but I was stumped and I had to look at other sources for the code in regards to bouncing off the paddle in a reflective manner. I was curious about two methods (checkPaddle and checkPaddle2), I understand it says that if the ball intersects with either paddle, it will update the counter and bounce off. Can anyone help explain to me what the dX and dY part (where it says int offset = .......) is saying? Thank you.
My code is below.
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 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 | import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) /** * Write a description of class Ball here. * * @author (your name) * @version (a version number or a date) */ public class Ball extends Actor { private int dX; private int dY; /** * Act - do whatever the Ball wants to do. This method is called whenever * the 'Act' or 'Run' button gets pressed in the environment. */ public void act() { move( 9 ); checkOut(); turnAtEdge(); checkPaddle(); checkPaddle2(); checkBlock(); } private void checkWalls() { if (getX() == 0 || getX() == getWorld().getWidth()- 1 ) { dX = -dX; } if (getY() == 0 ) { dY = -dY; } } public boolean CheckEdge() { if (getX() < 2 || getX() > getWorld().getWidth() - 10 ) return true ; if (getY() < 2 || getY() > getWorld().getHeight() - 10 ) return true ; else return false ; } private void checkOut() { if (getY() < 2 || getY() > getWorld().getHeight() - 10 ) { Greenfoot.stop(); PongWorld pong = (PongWorld) getWorld(); pong.addLoseMessage(); } } public void checkBlock() { Actor block = getOneIntersectingObject(Block. class ); if (block != null ) { getWorld().removeObject(block); turn(Greenfoot.getRandomNumber( 361 )); PongWorld pong = (PongWorld) getWorld(); pong.updateCount(); } } public void turnAtEdge() { if (CheckEdge()) { turn(Greenfoot.getRandomNumber( 361 )); } } public void checkPaddle() { Actor paddle = getOneIntersectingObject(Paddle. class ); if (paddle!= null ) { dY = -dY; int offset = getX() - paddle.getX(); dX = dX + (offset/ 10 ); if (dX > 7 ) { dX = 23 ; } if (dX < - 7 ) { dX = - 57 ; } PongWorld pong = (PongWorld) getWorld(); pong.updateCount(); } } public void checkPaddle2() { Actor paddle2 = getOneIntersectingObject(Paddle2. class ); if (paddle2!= null ) { dY = -dY; int offset = getX() - paddle2.getX(); dX = dX + (offset/ 10 ); if (dX > 7 ) { dX = 23 ; } if (dX < - 7 ) { dX = - 57 ; } PongWorld pong = (PongWorld) getWorld(); pong.updateCount(); } } } |