I'm working on a ping-pong style game (2d of course) and want to make it so the player can hit harder to make the ball go faster. I will only post the code that is relevant to the momentum. This is my current code for the paddle:
and for the ball:
I can compile without error but when I run it and the ball hits the player paddle I get the error terminal saying
"java.lang.NullPointerException
at Ball.checkPaddleCollision(Ball.java:62) <-- if(playerpaddle.getPaddleMomentumX() != 999999 && playerpaddle.getPaddleMomentumY() != 999999)
at Ball.act(Ball.java:29) <-- checkPaddleCollision();
"
This might be because of the mouse.getX() thing, so if it is do you think I should just use getX() of the paddle, since it follows the mouse?
public class PlayerPaddle extends Actor { private int mouseYcalc, mouseXcalc; public int mouseX5, mouseX4, mouseX3, mouseX2, mouseX1, mouseY5, mouseY4, mouseY3, mouseY2, mouseY1 = 0; public void act() { calculatePaddleMomentum(); } public void calculatePaddleMomentum() { MouseInfo mouse = Greenfoot.getMouseInfo(); if(mouse != null) { mouseXcalc = mouse.getX(); mouseYcalc = mouse.getY(); mouseX5 = mouseX4; mouseX4 = mouseX3; mouseX3 = mouseX2; mouseX2 = mouseX1; mouseX1 = mouseXcalc; mouseY5 = mouseY4; mouseY4 = mouseY3; mouseY3 = mouseY2; mouseY2 = mouseY1; mouseY1 = mouseYcalc; } } public int getPaddleMomentumX() { MouseInfo mouse = Greenfoot.getMouseInfo(); if(mouse != null) { return ((int)(mouseX5 - mouseX1)); } else return 999999; // for error detection in Ball class } public int getPaddleMomentumY() { MouseInfo mouse = Greenfoot.getMouseInfo(); if(mouse != null) { return ((int)(mouseY5 - mouseY1)); } else return 999999; // for error detection in Ball class } }
public class Ball extends Actor { private String xDirection = "right"; Table world = (Table)getWorld(); PlayerPaddle playerpaddle = (PlayerPaddle)world.playerpaddle; //Physics: private double yMomentum = 10; private double xMomentum = 5; public void checkPaddleCollision() { if(wait5 == 0) { PlayerPaddle collidedBlue = (PlayerPaddle)getOneIntersectingObject(PlayerPaddle.class); if (collidedBlue != null && xDirection == "left") { if(playerpaddle.getPaddleMomentumX() != 999999 && playerpaddle.getPaddleMomentumY() != 999999) { xMomentum = playerpaddle.getPaddleMomentumX(); yMomentum = playerpaddle.getPaddleMomentumY(); xDirection = "right"; } } public void act() { if(wait5 > 0) { wait5 = (wait5 - 1); } checkPaddleCollision(); calcPhysics(); moveBall(); } } EnemyPaddle collidedRed = (EnemyPaddle)getOneIntersectingObject(EnemyPaddle.class); if (collidedRed != null && xDirection == "right") { xMomentum = ((Greenfoot.getRandomNumber(7) + 3) * -1); yMomentum = (((Greenfoot.getRandomNumber(3) - 4) * (Greenfoot.getRandomNumber(3) + 1))); xDirection = "left"; } } } }