![]() |
Bouncing Ball......Java Help
Hi,
I need some help on my code which I am using in Blue J: [PHP]import ou.*; /** * The class Ball creates a ball which bounces and ricochets within the confines of the square inside the shapes window. * * @author (XXXXX) * @version (v1.0) */ public class Ball extends Circle { // instance variables private int x; /** * Constructor for objects of class Ball */ public Ball() { // initialise instance variables x = 0; } /** * Slows down the movement of the ball within the shapes window */ private void delay(int time) { try { Thread.sleep(time); } catch (Exception e) { System.out.println(e); } } /** * Moves the receiver to the position specified by the arguments xPos and yPos */ public void moveTo(int xPos, int yPos) { this.setXPos(xPos); this.setYPos(yPos); this.update(); } /** * Changes the colour of the receiver as follows */ public void changeColour() { if(this.getColour() == OUColour.BLUE) { this.setColour(OUColour.RED); } else if(this.getColour() == OUColour.RED) { this.setColour(OUColour.GREEN); } else { this.setColour(OUColour.BLUE); } } /** * Sets the position of the yPos such that the ball appears to be bouncing */ public void singleBounce() { while(this.getYPos()<250) { this.setYPos(this.getYPos()+10); this.delay(10); } while(this.getYPos() + 20 != this.getYPos()) { this.setYPos(this.getYPos()-10); this.delay(10); } } }[/PHP] The problem is that the above code is for the Class Ball, The code should works as follows: while the yPosition of the ball is less than 250, then the ball yPos should increment in steps of 10 (which I think I've done correctly), so that the ball appears to be moving downwards, (The problem is with the singlebounce method in the code) Then the yPos should be decremented in steps of 10 units, until the ball is 20 units below its original position so that the ball appears to bounce upwards in the Shapes window. This is where Im having all the problems, if you look at the code the ball bounces appears to move downwards,but on the way up I cant seem to stop it below 20 units its initial position. Can anyone help? Help is greatly appreciated. |
You need to rewrite your second while loop. Try to draw a picture of the ball on paper and step through the loop on paper.
|
Ive tried many times to draw on paper, but the thing is that I need to recall the original y position before I can lower it by 20 units.
I dont know how to recall the yPos function as the method for yPos returns void???? Do i use the super() function??? Is there any way u can use 'this' so that you can lower the position of the ball by 20 units??? |
Quote:
Starrboy |
Original Y position...
ps. this.getYPos() + 20 != this.getYPos() will always return false |
| All times are GMT -5. The time now is 7:56 AM. |
Powered by vBulletin® Version 3.7.0, Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Copyright ©2007 DaniWeb® LLC