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

2022/5/16

Ball being launched in a certain direction

Gengar360 Gengar360

2022/5/16

#
i am currently trying to make it so in my breakout game the ball will go in a certain direction depending on where the ball hits the paddle.
public class Ball extends Actor
{
    /**
     * Act - do whatever the Ball wants to do. This method is called whenever
     * the 'Act' or 'Run' button gets pressed in the environment.
     */
    int SpeedY = 5;
    int SpeedX = 0;
    public Paddle paddle;
    public World MyWorld;
    public void Ball(Paddle paddle, World world){
        MyWorld = world;
        this.paddle = paddle;
        GreenfootImage img = new GreenfootImage("ball.png");
        img.scale(img.getWidth()/12, img.getHeight()/12);
        setImage(img);
        Break();
    }
    public void act()
    {
        /**GreenfootImage img = new GreenfootImage("ball.png");
        img.scale(img.getWidth()/12, img.getHeight()/12);
        setImage(img);*/
        moveAround();
        bounce();
        Ball(paddle, MyWorld);
    }
    public void moveAround(){
        setLocation(getX() + SpeedX, getY() + SpeedY);
    }
    public void bounce(){
        if((isTouching(Paddle.class) || isTouching(Block_1.class)) && this.paddle.getX() < getX()){ 
            SpeedY = -SpeedY;
        }
    }
    public void Break(){
        Actor Block = getOneIntersectingObject(Block_1.class);
        if(Block != null){
            getWorld().removeObject(Block);
        }
this is the code for the ball but it gives me an error message im not sure how to fix this
Spock47 Spock47

2022/5/16

#
It seems that "this.paddle" is null. Therefore: 1. Please give the source code where the constructor is called (new Ball(..., ...)). (if the first parameter is null, we found the problem) 2. Please change the line "public Paddle paddle;" to "private final Paddle paddle;". This ensures that the constructor is the only place "this.paddle" is set (otherwise one would have to check whether paddle gets changed somewhere else in the source code).
You need to login to post a reply.