This site requires JavaScript, please enable it in your browser!
Greenfoot back
tn13673
tn13673 wrote ...

2016/3/9

How do I get this to bounce now? My teacher says I don't have the code in there for it and look in our notes, but I can't find it.

tn13673 tn13673

2016/3/9

#
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 { public int xspeed = 4; public int yspeed = 4; public static int ballX, ballY; /** * Act - do whatever the paddle wants to do. This method is called whenever * the 'Act' or 'Run' button gets pressed in the environment. */ public void act() { setLocation(getX() + xspeed, getY()+yspeed); bounce(); ballX = getX (); ballY = getY (); } public void bounce() { int worldWidth = getWorld().getWidth(); int worldHeight = getWorld().getHeight(); int spriteWidth = getImage().getWidth()/2; int spriteHieght = getImage().getHeight()/2; if(getX() <= spriteWidth) xspeed = xspeed * -1; if(getX() >= spriteWidth - spriteWidth) xspeed = xspeed * -1; if(getY() <= spriteHieght) yspeed = yspeed * -1; if(getY() <= spriteHieght) yspeed = yspeed * -1; } }
danpost danpost

2016/3/9

#
Your 'bounce' method with line numbers follows:
public void bounce()
{
    int worldWidth = getWorld().getWidth();
    int worldHeight = getWorld().getHeight();
    int spriteWidth = getImage().getWidth()/2;
    int spriteHieght = getImage().getHeight()/2;

    if (getX() <= spriteWidth)
        xspeed = xspeed * -1;
    
    if (getX() >= spriteWidth - spriteWidth)
        xspeed = xspeed * -1;
    
    if (getY() <= spriteHieght)
        yspeed = yspeed * -1;
     
    if (getY() <= spriteHieght)
        yspeed = yspeed * -1;
}
Line 11 is suspicious in that you are comparing 'getX' to zero ( 'spriteWidth - spriteWidth' ). Also, lines 14 and 17 use the same comparisons for their 'if' conditions. HINT: the local variables 'worldWidth' and 'worldHeight' are not used after being assigned values.
You need to login to post a reply.