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

2016/1/7

Help!!! I am making a vertical ping pong game and the ball wont bounce off left side

velasmic002 velasmic002

2016/1/7

#
this is the code:
import greenfoot.*;  // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)

/**
 * Write a description of class Gem here.
 * 
 * @author (your name) 
 * @version (a version number or a date)
 */
public class Gem extends All
{
    
    public int xSpeed= 3;
    public int ySpeed= 3;
    /**
     * Act - do whatever the Gem wants to do. This method is called whenever
     * the 'Act' or 'Run' button gets pressed in the environment.
     */
    public void act() 
    {
       move();
       paddleBounce();
       wallBounce();
    }
     public void move()
     {setLocation( getX() + xSpeed, getY() + ySpeed);
        }
    public void wallBounce()
    {
        if(getX() >= getWorld().getWidth()-getImage().getWidth()/2)
    {
        xSpeed= xSpeed *-1;
       
}
 if(getY() >= getWorld().getHeight()-getImage().getHeight()/2)
    {
        ySpeed= ySpeed * 1;
       
}
 }   
  
public Gem()
{
    GreenfootImage myImage = getImage();
    int myNewHeight = (int)myImage.getHeight()/12;
    int myNewWidth = (int)myImage.getWidth()/12;
    myImage.scale(myNewWidth, myNewHeight);
}
public void paddleBounce()
{
    Actor bar = getOneIntersectingObject(Bar.class);
    if(bar !=null)
    {
    ySpeed=ySpeed*-1;
}
 Actor ComputerBar = getOneIntersectingObject(ComputerBar.class);
 if(ComputerBar !=null)
 {
     ySpeed=ySpeed*-1;
    }
}
}
davmac davmac

2016/1/7

#
Please indent your code properly (see this page). The problem is that your code (in the wallBounce() method) only checks if the ball reaches the right-hand wall. It does not check if the ball reaches the left wall. Quite simply, there is no code to make the ball bounce off the left-hand wall, and so it doesn't. You check for collision with the right-hand wall with this code:
        if(getX() >= getWorld().getWidth()-getImage().getWidth()/2)
That is, it checks if the current X co-ordinate (getX()) is near the right-hand edge of the world (getWorld().getWidth()). It adds a small margin to account for the size of the ball itself (-getImage().getWidth()/2). If you think about this for a little bit you should be able to adapt it to check for collision with the left-hand wall instead.
You need to login to post a reply.