java applet game jumping bug - java

I'm currently making a java game and I just managed to make the character jump but it only works half the time.
Sometimes he will jump perfectly but other times he will get stuck in the air. I think its something to do with the gravity variable changing but I'm not sure Please can you have a look?
import java.applet.Applet;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.Timer;
import java.util.TimerTask;
public class meatboy extends Applet implements KeyListener{
public int x = 10, y = 300, gravity = 3;
public int xs = 380, ys = 230 , jump_count, jump_move;
double jumptime = 0;
public boolean right, left, up, jump = true, start, grounded, grav = true;
public void init(){
setSize(800,400);
setBackground(Color.black);
addKeyListener(this);
/////Movement//////
Timer t = new Timer();
t.schedule(new TimerTask(){public void run(){
if (start == true){
if (right == true){
x = x + 3;
}if (left == true){
x = x - 3;
}if(up == true && jump == true){
jump_count++;
if (jump_count >= 100){
jump_count = 0;
}
if (jump_count >= 0 && jump_count <= 25){
//jump_move = 1;
y = y - 5;
}
if (jump_count >= 25 && jump_count <= 50){
//jump_move = 2;
y = y - 5;
}
if (jump_count >= 50 && jump_count <= 75){
//jump_move = 3;
y = y - 5;
}
if (jump_count >= 75 && jump_count <= 100){
//jump_move = 0;
y = y - 5;
jump = false;
}
}
/////GRAVITY//////
if (grav == true){y = y + gravity;}
///////Collision Dectection/////
if(x > 790){//right of screen stop
x = 10;
}if(x < 10){// left stop
x = 789;
}if(y > 350){
//y = y - 3;
grav = false;
jump = true;
}else{grav = true;}
////////////End of collision///////////
repaint();
}}},10,10);
///////movement end////////
}
public void paint(Graphics g){
////////CREATES MEATBOY///////////////
if (start == false){
x = 10;
y = 300;
g.setColor(Color.DARK_GRAY);
g.fillRect(0, 0, 800, 400);
g.setColor(Color.white);
g.drawString("MeatBoy 4K", 358, 180);
g.drawString("Press Z to start!!!!", 350, 200);
g.setColor(Color.RED);
g.fillRect(xs, ys, 16, 16);//meatboys body
g.fillRect(xs + 16, ys + 6, 4, 4);//arm
g.fillRect(xs - 4, ys + 6, 4, 4);//arm
g.fillRect(xs, ys + 12, 4, 6);//leg
g.fillRect(xs + 12, ys + 12, 4, 6);//leg
g.setColor(Color.black);
g.fillRect(xs + 2, ys + 2, 5, 5);//eye
g.fillRect(xs + 10, ys + 2, 5, 5);//eye
}
if (start == true){
g.setColor(Color.RED);
g.fillRect(x, y, 16, 16);//meatboys body
g.fillRect(x + 16, y + 6, 4, 4);//arm
g.fillRect(x - 4, y + 6, 4, 4);//arm
g.fillRect(x, y + 12, 4, 6);//leg
g.fillRect(x + 12, y + 12, 4, 6);//leg
g.setColor(Color.black);
g.fillRect(x + 2, y + 2, 5, 5);//eye
g.fillRect(x + 10, y + 2, 5, 5);//eye
///////////END OF MEATBOY//////////////////
////////Creates Floor///////////////////
g.setColor(Color.GRAY);
g.fillRect(0, 370, 800, 30);
}
}
/**
*
*/
private static final long serialVersionUID = 1L;
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_Z){
//right = true;
start = true;
}
if (e.getKeyCode() == KeyEvent.VK_RIGHT){
//right = true;
right = true;
}if (e.getKeyCode() == KeyEvent.VK_LEFT){
left = true;
}if (e.getKeyCode() == KeyEvent.VK_UP){
up = true;
}if (e.getKeyCode() == KeyEvent.VK_SPACE){
up = true;
}
}
public void keyReleased(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_RIGHT){
//right = true;
right = false;
}if (e.getKeyCode() == KeyEvent.VK_LEFT){
left = false;
}if (e.getKeyCode() == KeyEvent.VK_UP){
up = false;
}if (e.getKeyCode() == KeyEvent.VK_SPACE){
up = false;
}
}
public void keyTyped(KeyEvent e) {
}
}

Where does the player get stuck in the air?
If it's close to the ground, make sure that the y coordinate is right on the ground.
On this block of code:
}if(y > 350){
//y = y - 3;
grav = false;
jump = true;
}else{grav = true;}
Add
}if(y > 350){
//y = y - 3;
grav = false;
jump = true;
//I'm on the ground all right
y = 350;
}else{grav = true;}

Related

How to fix this NullPointerException from my Platformer Game?

I am trying to make a Platformer game where you can run around and jump off the base of rectangles and off the sides of them.
I am compiling this in Processing 2.2.1. The program does not run. I am also looking for help on how to implement a jump and when to change the character's image.
speed = 0;
int numrects = 9;
Player player1 = new Player();
//Rectangle[] platforms = new Rectangle[16];
public static Rectangle[] platforms = new Rectangle[16];
class Player{
PImage[] images = new PImage[10];
int xMove, yMove, xSpeed, ySpeed, gravity, jumpheight, xSize, ySize;
boolean a = true;
boolean d = true;
boolean w = true;
int x, y;
int numFrames = 7; // The number of animation frames
int frame = 0; // The frame to display
PImage img;
Player (){
xSpeed = 10;
ySpeed = 10;
xSize = 24;
ySize = 51;
x = width/2;
y = height/2;
}
void jump() {
for (int x = 0; x <= jumpheight; x++){
y = y + gravity;
image(images[frame], x, y);
}
for (int x = 0; x <= jumpheight; x++){
y = y - gravity;
image(images[frame], x, y);
}
}
};
class Rectangle{
int x, y, xSize, ySize;
//.fill(127);
Rectangle(){
x = 1;
y = 1;
xSize = 10;
ySize = 10;
}
void build(int newx, int newy, int newxSize, int newySize){
x = newx;
y = newy;
xSize = newxSize;
ySize = newySize;
rect (x, y, xSize, ySize);
}
};
void setup() {
size(1920, 1080);
frameRate(30);
player1.images[0] = loadImage("Staticl.png");
player1.images[3] = loadImage("Staticr.png");
player1.images[1] = loadImage("step1left.png");
player1.images[4] = loadImage("step1right.png");
player1.images[2] = loadImage("step2left.png");
player1.images[5] = loadImage("step2right.png");
//images[3] = loadImage("1.jpg");
//images[7] = loadImage("2.jpg");
player1.xSpeed = 10;
player1.x = 500;
player1.y = 500;
platforms[0].build(0, 837, 1920, 244);
platforms[1].build(0, 765, 294, 23);
platforms[2].build(733, 725, 734, 39);
platforms[3].build(0, 765, 294, 23);
platforms[4].build(0, 765, 294, 23);
platforms[5].build(1306, 569, 161, 195);
platforms[6].build(558, 607, 653, 33);
platforms[7].build(0, 522, 496, 34);
platforms[8].build(477, 360, 173, 37);
platforms[9].build(690, 288, 445, 34);
platforms[10].build(1149, 174, 217, 40);
platforms[11].build(1390, 298, 243, 33);
platforms[12].build(1488, 490, 167, 30);
platforms[13].build(1690, 301, 138, 31);
platforms[14].build(1693, 426, 227, 27);
platforms[15].build(1866, 226, 54, 199);
}
void checkforcollision(){
for (int x = 0; x <= numrects; x++){
if (player1.x + player1.xSize == platforms[x].x && player1.y <= platforms[x].y + platforms[x].ySize && player1.y + player1.ySize >= platforms[x].y){
// right side of box hits left side of platform
player1.d = false;
player1.w = true;
}
else if(player1.x == platforms[x].x + platforms[x].xSize && player1.y <= platforms[x].y + platforms[x].ySize && player1.y + player1.ySize >= platforms[x].y){
// left side of box hits right side of platform
player1.a = false;
player1.w = true;
}
else if(player1.y + player1.ySize == platforms[x].y && player1.x <= platforms[x].x + platforms[x].xSize && player1.x + player1.xSize >= platforms[x].x){
// bottom of player hits top of box
player1.w = false;
}
else if(player1.y == platforms[x].y + platforms[x].ySize && player1.x <= platforms[x].x + platforms[x].xSize && player1.x + player1.xSize >= platforms[x].x){
// top of player hits bottom of box
player1.w = true;
player1.a = true;
player1.d = true;
}
else {
player1.w = false;
player1.a = true;
player1.d = true;
}
}
}
void draw() {
checkforcollision();
if (player1.d == true)
player1.x = player1.x + player1.xSpeed;
image(player1.images[player1.frame], player1.x, player1.y);
if (player1.a == true)
player1.x = player1.x - player1.xSpeed;
image(player1.images[player1.frame], player1.x, player1.y);
if (player1.w == true)
player1.jump();
//image(images[frame], player1.x, player1.y);
}
void keyPressed() {
if ((key == 'a') || (key == 'A')){
player1.a = true;
}
else if ((key == 'd') || (key == 'D')){
player1.d = true;
}
else if ((key == 'w') || (key == 'W')){
player1.w = true;
}
}
void keyReleased() {
if ((key == 'a') || (key == 'A')){
player1.a = false;
}
else if ((key == 'd') || (key == 'D')){
player1.d = false;
}
}
The NullPointerException is because you haven't initialized the Rectangles in the array yet. So this line causes an error:
platforms[0].build(0, 837, 1920, 244);
First, you need to run something like this:
for (int i=0; i<platforms.length; i++) {
platforms[i] = new Rectangle();
}

Incorporating random maze generation into my game (Java)

I am currently making a maze solving game in Java, and I am currently running into a snag. All of the random maze generation algorithms that I could find output in a way that I couldn't figure out how to implement into my current code. I was considering using the Depth First Search, Recursive Backtracker, or Prim's Algorithm, since I thought they would be the easiest to implement while still generating good mazes. What would be a working use of one of those algorithms that works with my current program? This is my Game Class: (Feel free to point out any bad practices as well, I am pretty new to Java)
package game;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Game extends JPanel implements ActionListener, KeyListener {
private boolean upPressed = false;
private boolean downPressed = false;
private boolean rightPressed = false;
private boolean leftPressed = false;
private final int playerDiam = 100;
private final int playerSpeed = 15;
private final int tileSize = 400;
private int[][] maze = {{1, 1, 1, 1, 1, 1},
{1, 2, 1, 1, 3, 1},
{1, 0, 1, 0, 0, 1},
{1, 0, 1, 0, 1, 1},
{1, 0, 0, 0, 1, 1},
{1, 1, 1, 1, 1, 1},
};
private int[][] initX = new int[maze.length][maze.length];
private int[][] initY = new int[maze.length][maze.length];
private int deltaX = -210;
private int deltaY = -210;
private String screen = "menu";
public Game() {
setFocusable(true);
addKeyListener(this);
setUpInitialCoordinates();
Timer timer = new Timer(1000 / 60, this);
timer.start();
}
#Override
public void actionPerformed(ActionEvent e) {
tick();
}
private void setUpInitialCoordinates() {
int x = 0;
int y;
for (int[] rowData : maze) {
y = 0;
for (int ignored : rowData) {
initX[x][y] = x * tileSize;
initY[x][y] = y * tileSize;
y++;
}
x++;
}
}
private void generateMaze() {
}
private void tick() {
if (screen.equals("playing")) {
if (upPressed) {
deltaY += playerSpeed;
} else if (downPressed) {
deltaY -= playerSpeed;
}
if (rightPressed) {
deltaX -= playerSpeed;
} else if (leftPressed) {
deltaX += playerSpeed;
}
}
repaint();
}
#Override
public void keyTyped(KeyEvent e) {}
#Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_UP || e.getKeyCode() == KeyEvent.VK_W) {
upPressed = true;
} else if (e.getKeyCode() == KeyEvent.VK_DOWN || e.getKeyCode() == KeyEvent.VK_S) {
downPressed = true;
} else if (e.getKeyCode() == KeyEvent.VK_RIGHT || e.getKeyCode() == KeyEvent.VK_D) {
rightPressed = true;
} else if (e.getKeyCode() == KeyEvent.VK_LEFT || e.getKeyCode() == KeyEvent.VK_A) {
leftPressed = true;
}
}
#Override
public void keyReleased(KeyEvent e) {
if (screen.equals("menu") && e.getKeyCode() == KeyEvent.VK_ENTER) {
upPressed = false;
downPressed = false;
rightPressed = false;
leftPressed = false;
screen = "playing";
} else if (screen.equals("playing")) {
if (e.getKeyCode() == KeyEvent.VK_UP || e.getKeyCode() == KeyEvent.VK_W) {
upPressed = false;
} else if (e.getKeyCode() == KeyEvent.VK_DOWN || e.getKeyCode() == KeyEvent.VK_S) {
downPressed = false;
} else if (e.getKeyCode() == KeyEvent.VK_RIGHT || e.getKeyCode() == KeyEvent.VK_D) {
rightPressed = false;
} else if (e.getKeyCode() == KeyEvent.VK_LEFT || e.getKeyCode() == KeyEvent.VK_A) {
leftPressed = false;
} else if (e.getKeyCode() == KeyEvent.VK_P) {
screen = "paused";
}
} else if (screen.equals("paused" ) && e.getKeyCode() == KeyEvent.VK_P) {
upPressed = false;
downPressed = false;
rightPressed = false;
leftPressed = false;
screen = "playing";
}
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setFont(new Font("Aharoni", Font.PLAIN, 36));
g.setColor(Color.WHITE);
g.fillRect(0, 0, getWidth(), getHeight());
switch (screen) {
case "menu":
g.setColor(Color.BLACK);
g.drawString("Labyrinth", 300, 200);
g.drawString("Press Enter to Play!", getWidth() / 3, 500);
break;
case "playing":
int x = 0;
int y = 0;
for (int[] rowData : maze) {
for (int cellData : rowData) {
if (cellData == 1) {
g.setColor(Color.DARK_GRAY);
g.fillRect(x + deltaX, y + deltaY, tileSize, tileSize);
} else if (cellData == 2) {
g.setColor(Color.GREEN);
g.fillRect(x + deltaX, y + deltaY, tileSize, tileSize);
} else if (cellData == 3) {
g.setColor(Color.YELLOW);
g.fillRect(x + deltaX, y + deltaY, tileSize, tileSize);
}
x += tileSize;
if (x == maze.length * tileSize) {
x = 0;
y += tileSize;
}
}
} g.setColor(Color.RED);
g.fillOval(getWidth() / 2, getHeight() / 2, playerDiam, playerDiam);
break;
case "gameOver":
g.setColor(Color.BLACK);
g.drawString("Game Over",getWidth() / 3 ,50 );
break;
case "paused":
g.setColor(Color.BLACK);
g.drawString("Paused", getWidth() / 3, 50);
break;
}
}
}
as start I would
clear maze
randomly add walls
create random path for all entry/exit points pairs present
clear the maze cells along them.
If you just need maze solver (some algos for maze generation needs them)
then look here How to speed up A* algorithm at large spatial scales?
with use of solver you can change algorithm to
clear maze
add random wall
if adding it still provides solution
loop bullet(2) N times
You need to be careful about how to add the walls
for example if you add just simple lines then the maze will look like this:
This is the code for it (uses the class from linked answer)
// generate random maze with path from x0,y0 to x1,y1 present, n walls
void A_star::generate(int x0,int y0,int x1,int y1,int n)
{
int x,y,i,j,dx,dy,l,*p;
// [clear map]
for (y=0;y<ys;y++)
for (x=0;x<xs;x++)
map[y][x]=A_star_space;
// temp space
p=new int [xs>>1]; if (p==NULL) return;
// generate n walls
for (i=0;i<n;i++)
{
// random start pos,dir,length
x =Random(xs);
y =Random(ys);
dx=Random(4);
l =Random(xs>>2)+2;
if (dx==0) { dx=+1; dy= 0; }
else if (dx==1) { dx=-1; dy= 0; }
else if (dx==2) { dx= 0; dy=+1; }
else if (dx==3) { dx= 0; dy=-1; }
// add wall to maze remember set cells (for remowal if needed)
for (j=0;l;l--,x+=dx,y+=dy)
if ((x>=0)&&(x<xs))
if ((y>=0)&&(y<ys))
if (map[y][x]!=A_star_wall)
{
p[j]=x; j++;
p[j]=y; j++;
map[y][x]=A_star_wall;
}
// is there solution?
compute(x0,y0,x1,y1);
// if not remowe last added wall
if (ps==0) for (;j;)
{
j--; y=p[j];
j--; x=p[j];
map[y][x]=A_star_space;
}
}
delete[] p;
}
generated by this code:
A_star map;
map.resize(256,256);
map.generate(5,5,250,250,500);

JFrame won't call paint method?

So I made Pong in a applet for a project in school but I realized that I can't hand in the project without creating an HTML file, so I'm attempting to change all my code from a applet to a JFrame. It all works, but my paint method isn't being called, any help will be great. Thanks for the help but to be honest im new to programming so if someone could make the changes to my code and then explain what you did, that would be great
package pong;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
class Main extends JPanel implements Runnable, KeyListener{//whatever class holds you main method
private static final long serialVersionUID = 1L;
int width = 600;
int height = width *9/16;
int Pwidth = 10, Pheight = 50, Px = 30, Py = height / 2-Pwidth, Pv = 3;
int Ewidth = 10, Eheight = 50, Ex = width - Ewidth - 30, Ey = height / 2-Ewidth - 50;
double Ev = 2.7;
int Bwidth = 10, Bheight = 10, Bx = width / 2 + 50, By = height / 2, Bvx = 3, Bvy = 3;
int TimeD = 0;
int Ms = 0, sec = 0, min = 0;
int Pscore = 0, Escore = 0, Pwinx = 800, Pwiny = height / 2, Ewinx = 800, Ewiny = height / 2;
boolean Bleft = true, Bright = false, Bup = true, Bdown = false;
boolean Pup = false, Pdown = false;
boolean Pa = false;
String string = new String();
public static JFrame frame;//public and static so other classes can access it. Might want to use a getter and setter here
public Main(){
frame=new JFrame("Pong, A game re-made by Camron Warren");// Create new JFrame
frame.setSize(width,height);//Set the size of the window
frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE);//Make sure all processes are closed when the window is closed
frame.setLocationRelativeTo(null);//Centers window
frame.setVisible(true);//Make the window visible
Thread th = new Thread(this);
addKeyListener(this);
th.start();
}
public static void main(String[] args){
new Main();//instantiate the Main class, this has to happen
}
#Override
public void run() {
while(true){
if(Pscore >= 5){
Pwinx = 100;
Py = height / 2 - Pheight / 2;
Bx = width / 2 - Bwidth;
By = height /2 - Bheight /2;
}
if(Escore >= 5){
Ewinx = 400;
Py = height / 2-Pwidth;
Bx = width / 2 - Bwidth;
By = height /2;
}
if(Escore >= 5 && Pa == true){
Pscore = 0;
Escore = 0;
Ewinx = 800;
Ms = 0;
sec = 0;
min = 0;
}
if(Pscore >= 5 && Pa == true){
Pscore = 0;
Escore = 0;
Pwinx = 800;
Ms = 0;
sec = 0;
min = 0;
}
//ball movement class
ballMovement();
//TIME COUNTER
Ms++;
if(Ms >= 60){
sec++;
Ms = 0;
}
if(sec >= 60){
min++;
sec = 0;
}
//BALLMOVEMENT
if(Bleft == true){
Bx-=Bvx;
}
if(Bright == true){
Bx+=Bvx;
}
if(Bup == true){
By-=Bvy;
}
if(Bdown == true){
By+=Bvy;
}
//BALLHITBOX
if(By <= 0){
Bup = false;
Bdown = true;
}
if(By + Bheight >= height){
Bdown = false;
Bup = true;
}
//SCORE SYSTEM
if(Bx <= 0){
Escore++;
Bx = width / 2 - Bwidth;
By = height / 2;
}
if(Bx+Bwidth >= width){
Pscore++;
Bx = width /2 - Bwidth;
By = height / 2;
}
//PHITBOX
if(Bx+Bwidth >= Px && Bx <= Px+Pwidth && By+Bheight >= Py && By <= Py+Pheight){
System.out.println("Phit");
Bleft = false;
Bright = true;
}
//EHITBOX
if(Bx+Bwidth >= Ex && Bx <= Ex + Ewidth && By+Bheight >= Ey && By <= Ey + Eheight){
System.out.println("Ehit");
Bright = false;
Bleft = true;
}
//PMOVEMENT
if(Pup == true){
Py-=Pv;
}
if(Pdown == true){
Py+=Pv;
}
//PHITBOX/APPLETHITBOX
if(Py <= 0){
Py = 0;
}
if(Py + Pheight >= height){
Py = height - Pheight;
}
//EHITBOX/APPLETHITBOX
if(Ey <= 0){
Ey = 0;
}
if(Ey + Eheight >= height){
Ey = height - Eheight;
}
//REPAINT
repaint();
try {
Thread.sleep(17);
} catch (InterruptedException e){
e.printStackTrace();
}
}
}
public void ballMovement()
{
if(By >= Ey)
{
Ey += Ev;
}
if(By <= Ey)
{
Ey -= Ev;
}
}
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if(key == KeyEvent.VK_W){
Pup = true;
}
if(key == KeyEvent.VK_S){
Pdown = true;
}
if(key == KeyEvent.VK_UP){
Pup = true;
}
if(key == KeyEvent.VK_DOWN){
Pdown = true;
}
if(key == KeyEvent.VK_F1){
Pa = true;
}
}
public void keyReleased(KeyEvent e) {
int key = e.getKeyCode();
if(key == KeyEvent.VK_W){
Pup = false;
}
if(key == KeyEvent.VK_S){
Pdown = false;
}
if(key == KeyEvent.VK_UP){
Pup = false;
}
if(key == KeyEvent.VK_DOWN){
Pdown = false;
}
if(key == KeyEvent.VK_F1){
Pa = false;
}
}
#Override
public void keyTyped(KeyEvent arg0) {}
#SuppressWarnings("deprecation")
public void update(Graphics g) {
Graphics offgc;
Image offscreen = null;
Dimension d = size();
offscreen = createImage(d.width, d.height);
offgc = offscreen.getGraphics();
offgc.setColor(getBackground());
offgc.fillRect(0, 0, d.width, d.height);
offgc.setColor(getForeground());
paint(offgc);
g.drawImage(offscreen, 0, 0, this);
}
#Override
public void paint(Graphics g){
g.setColor(Color.green);
g.fillRect(Px, Py, Pwidth, Pheight);
g.setColor(Color.RED);
g.fillRect(Ex, Ey, Ewidth, Eheight);
g.setColor(Color.BLACK);
g.fillOval(Bx, By, Bwidth, Bheight);
g.setColor(Color.BLACK);
g.drawRect(0, 0, width - 1, height - 1);
g.drawString("Score: " + Pscore, 20, 20);
g.drawString("Score " + Escore , width - 60, 20);
g.drawString("Time played: " + min + ": " + sec, width / 2 - 50, 20);
g.setColor(Color.BLACK);
g.fillRect(width / 2, height, 1, height);
g.setColor(Color.BLACK);
g.drawLine(width / 2, 0, width / 2, height);
g.setColor(Color.BLACK);
g.drawString("Pong: a game re-made by Camron Warren", 10, height - 10);
g.drawString("Congrat's, you win!", Pwinx, Pwiny);
g.drawString("Press F1 to play again!", Pwinx, Pwiny + 10);
g.drawString("Enemy win's", Ewinx, Ewiny);
g.drawString("Press F1 to play again!", Ewinx, Ewiny + 10);
}
}

Why I'm getting ArrayIndexOutOfBoundsException? [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 9 years ago.
I'm creating a pacman game, and I'm getting an exception that I can't figure out:
Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: -11
at p.PacBoard.moveGhosts(PacBoard.java:207)
And here is where the logic of my game is (I marked off the line that has thrown the exception):
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Event;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.ImageIcon;
import javax.swing.JPanel;
import javax.swing.Timer;
public class PacBoard extends JPanel implements ActionListener {
Dimension d;
String s = "Press s to start.";;
Font small = new Font("Helvetica", Font.BOLD, 14);
FontMetrics metr = this.getFontMetrics(small);
Image ii;
Color dotcolor = new Color(192, 192, 0);
Color mazecolor;
boolean ingame = false;
boolean dying = false;
final int blocksize = 24;
final int nrofblocks = 15;
final int scrsize = nrofblocks * blocksize;
final int pacanimdelay = 2;
final int pacmananimcount = 4;
final int maxghosts = 6;
final int pacmanspeed = 6;
int pacanimcount = pacanimdelay;
int pacanimdir = 1;
int pacmananimpos = 0;
int nrofghosts = 4;
int pacsleft, score;
int deathcounter;
int[] dx, dy;
int[] ghostx, ghosty, ghostdx, ghostdy, ghostspeed;
Image ghost;
Image pacman1, pacman2up, pacman2left, pacman2right, pacman2down;
Image pacman3up, pacman3down, pacman3left, pacman3right;
Image pacman4up, pacman4down, pacman4left, pacman4right;
int pacmanx, pacmany, pacmandx, pacmandy;
int reqdx, reqdy, viewdx, viewdy;
final short leveldata[] =
{ 3, 19, 18, 18, 18, 18, 18, 18, 18, 18, 18, 22, 3, 10, 6,
1, 25, 24, 16, 16, 16, 16, 16, 16, 16, 16, 20, 5, 15, 5,
1, 0, 0, 17, 16, 16, 16, 16, 16, 16, 16, 20, 9, 10, 12,
19, 18, 18, 16, 16, 16, 24, 16, 24, 16, 16, 24, 18, 18, 22,
17, 16, 16, 16, 16, 28, 0, 21, 0, 17, 20, 0, 17, 16, 20,
17, 16, 16, 16, 28, 0, 19, 20, 0, 25, 28, 0, 17, 16, 20,
17, 16, 16, 28, 0, 19, 16, 20, 0, 0, 0, 0, 17, 16, 20,
17, 16, 20, 0, 27, 16, 16, 16, 18, 18, 22, 0, 17, 16, 20,
17, 16, 16, 22, 0, 25, 16, 16, 16, 16, 20, 0, 17, 16, 20,
17, 16, 16, 16, 22, 0, 25, 16, 16, 16, 20, 0, 17, 16, 20,
17, 16, 16, 16, 16, 22, 0, 17, 16, 16, 20, 0, 17, 16, 20,
25, 16, 24, 16, 16, 16, 18, 16, 16, 16, 16, 18, 24, 24, 28,
1, 21, 0, 17, 16, 16, 16, 16, 16, 16, 16, 20, 0, 8, 12,
9, 29, 0, 17, 16, 16, 16, 16, 16, 16, 16, 20, 0, 10, 14,
9, 15, 27, 24, 24, 24, 24, 24, 24, 24, 24, 28, 8, 10, 14};
final int validspeeds[] = {1, 2, 3, 4, 5, 6};
final int maxspeed = 6;
int currentspeed = 3;
short[] screendata;
Timer timer;
public PacBoard() {
GetImages();
addKeyListener(new TAdapter());
screendata = new short[nrofblocks * nrofblocks];
mazecolor = new Color(255, 0, 5);
setFocusable(true);
d = new Dimension(400, 400);
setBackground(Color.black);
setDoubleBuffered(true);
ghostx = new int[maxghosts];
ghostdx = new int[maxghosts];
ghosty = new int[maxghosts];
ghostdy = new int[maxghosts];
ghostspeed = new int[maxghosts];
dx = new int[4];
dy = new int[4];
timer = new Timer(40, this);
timer.start();
}
public void addNotify() {
super.addNotify();
GameInit();
}
public void DoAnim() {
pacanimcount--;
if (pacanimcount <= 0) {
pacanimcount = pacanimdelay;
pacmananimpos = pacmananimpos + pacanimdir;
if (pacmananimpos == (pacmananimcount - 1) || pacmananimpos == 0)
pacanimdir = -pacanimdir;
}
}
public void PlayGame(Graphics2D g2d) {
if (dying) {
Death();
} else {
MovePacMan();
DrawPacMan(g2d);
moveGhosts(g2d);
CheckMaze();
}
}
public void ShowIntroScreen(Graphics2D g2d) {
g2d.setColor(new Color(0, 32, 48));
g2d.fillRect(50, scrsize / 2 - 30, scrsize - 100, 50);
g2d.setColor(Color.white);
g2d.drawRect(50, scrsize / 2 - 30, scrsize - 100, 50);
g2d.setColor(Color.white);
g2d.setFont(small);
g2d.drawString(s, (scrsize - metr.stringWidth(s)) / 2, scrsize / 2);
}
public void DrawScore(Graphics2D g) {
int i;
String s;
g.setFont(small);
g.setColor(new Color(96, 128, 255));
s = "Score: " + score;
g.drawString(s, scrsize / 2 + 96, scrsize + 16);
for (i = 0; i < pacsleft; i++) {
g.drawImage(pacman3left, i * 28 + 8, scrsize + 1, this);
}
}
public void CheckMaze() {
short i = 0;
boolean finished = true;
while (i < nrofblocks * nrofblocks && finished) {
if ((screendata[i] & 48) != 0)
finished = false;
i++;
}
if (finished) {
score += 50;
if (nrofghosts < maxghosts)
nrofghosts++;
if (currentspeed < maxspeed)
currentspeed++;
LevelInit();
}
}
public void Death() {
pacsleft--;
if (pacsleft == 0)
ingame = false;
LevelContinue();
}
public void moveGhosts(Graphics2D g2d) {
short i;
int pos;
int count;
for (i = 0; i < nrofghosts; i++) {
if (ghostx[i] % blocksize == 0 && ghosty[i] % blocksize == 0) {
pos = ghostx[i] / blocksize + nrofblocks * (int)(ghosty[i] / blocksize);
count = 0;
//line that causes problems below
if ((screendata[pos] & 1) == 0 && ghostdx[i] != 1) {
//line that causes problems above
dx[count] = -1;
dy[count] = 0;
count++;
}
if ((screendata[pos] & 2) == 0 && ghostdy[i] != 1) {
dx[count] = 0;
dy[count] = -1;
count++;
}
if ((screendata[pos] & 4) == 0 && ghostdx[i] != -1) {
dx[count] = 1;
dy[count] = 0;
count++;
}
if ((screendata[pos] & 8) == 0 && ghostdy[i] != -1) {
dx[count] = 0;
dy[count] = 1;
count++;
}
if (count == 0) {
if ((screendata[pos] & 15) == 15) {
ghostdx[i] = 0;
ghostdy[i] = 0;
} else {
ghostdx[i] = -ghostdx[i];
ghostdy[i] = -ghostdy[i];
}
} else {
count = (int)(Math.random() * count);
if (count > 3)
count = 3;
ghostdx[i] = dx[count];
ghostdy[i] = dy[count];
}
}
ghostx[i] = ghostx[i] + (ghostdx[i] * ghostspeed[i]);
ghosty[i] = ghosty[i] + (ghostdy[i] * ghostspeed[i]);
DrawGhost(g2d, ghostx[i] + 1, ghosty[i] + 1);
if (pacmanx > (ghostx[i] - 12) && pacmanx < (ghostx[i] + 12) &&
pacmany > (ghosty[i] - 12) && pacmany < (ghosty[i] + 12) &&
ingame) {
dying = true;
deathcounter = 64;
}
}
}
public void DrawGhost(Graphics2D g2d, int x, int y) {
g2d.drawImage(ghost, x, y, this);
}
public void MovePacMan() {
int pos;
short ch;
if (reqdx == -pacmandx && reqdy == -pacmandy) {
pacmandx = reqdx;
pacmandy = reqdy;
viewdx = pacmandx;
viewdy = pacmandy;
}
if (pacmanx % blocksize == 0 && pacmany % blocksize == 0) {
pos = pacmanx / blocksize + nrofblocks * (int)(pacmany / blocksize);
ch = screendata[pos];
if ((ch & 16) != 0) {
screendata[pos] = (short)(ch & 15);
score++;
}
if (reqdx != 0 || reqdy != 0) {
if (!((reqdx == -1 && reqdy == 0 && (ch & 1) != 0) ||
(reqdx == 1 && reqdy == 0 && (ch & 4) != 0) ||
(reqdx == 0 && reqdy == -1 && (ch & 2) != 0) ||
(reqdx == 0 && reqdy == 1 && (ch & 8) != 0))) {
pacmandx = reqdx;
pacmandy = reqdy;
viewdx = pacmandx;
viewdy = pacmandy;
}
}
// Check for standstill
if ((pacmandx == -1 && pacmandy == 0 && (ch & 1) != 0) ||
(pacmandx == 1 && pacmandy == 0 && (ch & 4) != 0) ||
(pacmandx == 0 && pacmandy == -1 && (ch & 2) != 0) ||
(pacmandx == 0 && pacmandy == 1 && (ch & 8) != 0)) {
pacmandx = 0;
pacmandy = 0;
}
}
pacmanx = pacmanx + pacmanspeed * pacmandx;
pacmany = pacmany + pacmanspeed * pacmandy;
}
public void DrawPacMan(Graphics2D g2d) {
if (viewdx == -1)
DrawPacManLeft(g2d);
else if (viewdx == 1)
DrawPacManRight(g2d);
else if (viewdy == -1)
DrawPacManUp(g2d);
else
DrawPacManDown(g2d);
}
public void DrawPacManUp(Graphics2D g2d) {
switch (pacmananimpos) {
case 1:
g2d.drawImage(pacman2up, pacmanx + 1, pacmany + 1, this);
break;
case 2:
g2d.drawImage(pacman3up, pacmanx + 1, pacmany + 1, this);
break;
case 3:
g2d.drawImage(pacman4up, pacmanx + 1, pacmany + 1, this);
break;
default:
g2d.drawImage(pacman1, pacmanx + 1, pacmany + 1, this);
break;
}
}
public void DrawPacManDown(Graphics2D g2d) {
switch (pacmananimpos) {
case 1:
g2d.drawImage(pacman2down, pacmanx + 1, pacmany + 1, this);
break;
case 2:
g2d.drawImage(pacman3down, pacmanx + 1, pacmany + 1, this);
break;
case 3:
g2d.drawImage(pacman4down, pacmanx + 1, pacmany + 1, this);
break;
default:
g2d.drawImage(pacman1, pacmanx + 1, pacmany + 1, this);
break;
}
}
public void DrawPacManLeft(Graphics2D g2d) {
switch (pacmananimpos) {
case 1:
g2d.drawImage(pacman2left, pacmanx + 1, pacmany + 1, this);
break;
case 2:
g2d.drawImage(pacman3left, pacmanx + 1, pacmany + 1, this);
break;
case 3:
g2d.drawImage(pacman4left, pacmanx + 1, pacmany + 1, this);
break;
default:
g2d.drawImage(pacman1, pacmanx + 1, pacmany + 1, this);
break;
}
}
public void DrawPacManRight(Graphics2D g2d) {
switch (pacmananimpos) {
case 1:
g2d.drawImage(pacman2right, pacmanx + 1, pacmany + 1, this);
break;
case 2:
g2d.drawImage(pacman3right, pacmanx + 1, pacmany + 1, this);
break;
case 3:
g2d.drawImage(pacman4right, pacmanx + 1, pacmany + 1, this);
break;
default:
g2d.drawImage(pacman1, pacmanx + 1, pacmany + 1, this);
break;
}
}
public void DrawMaze(Graphics2D g2d) {
short i = 0;
int x, y;
for (y = 0; y < scrsize; y += blocksize) {
for (x = 0; x < scrsize; x += blocksize) {
g2d.setColor(mazecolor);
g2d.setStroke(new BasicStroke(2));
if ((screendata[i] & 1) != 0) // draws left
{
g2d.drawLine(x, y, x, y + blocksize - 1);
}
if ((screendata[i] & 2) != 0) // draws top
{
g2d.drawLine(x, y, x + blocksize - 1, y);
}
if ((screendata[i] & 4) != 0) // draws right
{
g2d.drawLine(x + blocksize - 1, y, x + blocksize - 1,
y + blocksize - 1);
}
if ((screendata[i] & 8) != 0) // draws bottom
{
g2d.drawLine(x, y + blocksize - 1, x + blocksize - 1,
y + blocksize - 1);
}
if ((screendata[i] & 16) != 0) // draws point
{
g2d.setColor(dotcolor);
g2d.fillRect(x + 11, y + 11, 2, 2);
}
i++;
}
}
}
public void GameInit() {
pacsleft = 3;
score = 0;
LevelInit();
nrofghosts = 4;
currentspeed = 3;
}
public void LevelInit() {
int i;
for (i = 0; i < nrofblocks * nrofblocks; i++)
screendata[i] = leveldata[i];
LevelContinue();
}
public void LevelContinue() {
short i;
int dx = 1;
int random;
for (i = 0; i < nrofghosts; i++) {
ghosty[i] = 4 * blocksize;
ghostx[i] = 4 * blocksize;
ghostdy[i] = 0;
ghostdx[i] = dx;
dx = -dx;
random = (int)(Math.random() * (currentspeed + 1));
if (random > currentspeed)
random = currentspeed;
ghostspeed[i] = validspeeds[random];
}
pacmanx = 7 * blocksize;
pacmany = 11 * blocksize;
pacmandx = 0;
pacmandy = 0;
reqdx = 0;
reqdy = 0;
viewdx = -1;
viewdy = 0;
dying = false;
}
public void GetImages()
{
ghost = new ImageIcon(PacBoard.class.getResource("../pacpix/ghost.gif")).getImage();
pacman1 = new ImageIcon(PacBoard.class.getResource("../pacpix/pacman.png")).getImage();
pacman2up = new ImageIcon(PacBoard.class.getResource("../pacpix/up1.png")).getImage();
pacman3up = new ImageIcon(PacBoard.class.getResource("../pacpix/up2.png")).getImage();
pacman4up = new ImageIcon(PacBoard.class.getResource("../pacpix/up3.png")).getImage();
pacman2down = new ImageIcon(PacBoard.class.getResource("../pacpix/down1.png")).getImage();
pacman3down = new ImageIcon(PacBoard.class.getResource("../pacpix/down2.png")).getImage();
pacman4down = new ImageIcon(PacBoard.class.getResource("../pacpix/down3.png")).getImage();
pacman2left = new ImageIcon(PacBoard.class.getResource("../pacpix/left1.png")).getImage();
pacman3left = new ImageIcon(PacBoard.class.getResource("../pacpix/left2.png")).getImage();
pacman4left = new ImageIcon(PacBoard.class.getResource("../pacpix/left3.png")).getImage();
pacman2right = new ImageIcon(PacBoard.class.getResource("../pacpix/right1.png")).getImage();
pacman3right = new ImageIcon(PacBoard.class.getResource("../pacpix/right2.png")).getImage();
pacman4right = new ImageIcon(PacBoard.class.getResource("../pacpix/right3.png")).getImage();
}
public void paint(Graphics g)
{
super.paint(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setColor(Color.black);
g2d.fillRect(0, 0, d.width, d.height);
DrawMaze(g2d);
DrawScore(g2d);
DoAnim();
if (ingame){
PlayGame(g2d);
}
else{
ShowIntroScreen(g2d);
}
g.drawImage(ii, 5, 5, this);
Toolkit.getDefaultToolkit().sync();
g.dispose();
}
class TAdapter extends KeyAdapter {
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if (ingame)
{
if (key == KeyEvent.VK_LEFT)
{
reqdx=-1;
reqdy=0;
}
else if (key == KeyEvent.VK_RIGHT)
{
reqdx=1;
reqdy=0;
}
else if (key == KeyEvent.VK_UP)
{
reqdx=0;
reqdy=-1;
}
else if (key == KeyEvent.VK_DOWN)
{
reqdx=0;
reqdy=1;
}
else if (key == KeyEvent.VK_ESCAPE && timer.isRunning())
{
ingame=false;
}
else if (key == KeyEvent.VK_PAUSE) {
if (timer.isRunning())
timer.stop();
else timer.start();
}
}
else
{
if (key == 's' || key == 'S')
{
ingame=true;
GameInit();
}
}
}
public void keyReleased(KeyEvent e) {
int key = e.getKeyCode();
if (key == Event.LEFT || key == Event.RIGHT ||
key == Event.UP || key == Event.DOWN)
{
reqdx=0;
reqdy=0;
}
}
}
public void actionPerformed(ActionEvent e) {
repaint();
}
}
Sorry I know that's a lot of code but I'm not sure where the problem is being created. Here is the line that it is being caught at:
if ((screendata[pos] & 1) == 0 && ghostdx[i] != 1) {
I know it has to be increasing or decreasing the size of the array to an illegal number, but where? And why? That's what I don't understand. Oh, and I got the exception in my output window about 10 times, not sure why though. Would this mean it's getting increased in one of my for loops?
Thanks to anyone who will help, and I will provide more information as needed.
To compile:
import javax.swing.JFrame;
public class Pacman extends JFrame
{
public Pacman()
{
add(new PacBoard());
setTitle("Pacman");
setSize(380, 420);
setLocationRelativeTo(null);
setVisible(true);
}
public static void main(String[] args) {
new Pacman();
}
}
I think I know (with the help of other commenters) where your problem is:
We have deduced that either ghostx[i] is negative, or ghosty[i] is negative.
Notice here that you set dx to one, and then set ghostx[i] to dx.
The problem arises when you set dx to be the negative of dx (dx = -dx;)
This means that on the next iteration, dx is negative, and therefore out of bounds.
(It is out of bounds, because pos is calculated based on ghostx[i]. And ghostx[i] is calculated based on dx. If dx is negative, so will ghostx[i] be, and so will pos, causing big problems)
I am not sure what you were trying to do here, but definitely change this line and see if it fixes your problems. Leave a comment with what dx = -dx; is supposed to do, and I'll help you figure it out.
Code which is the culprit:
public void LevelContinue() {
short i;
int dx = 1;
int random;
for (i = 0; i < nrofghosts; i++) {
ghosty[i] = 4 * blocksize;
ghostx[i] = 4 * blocksize;
ghostdy[i] = 0;
ghostdx[i] = dx;
dx = -dx;//Line which kills your code
random = (int)(Math.random() * (currentspeed + 1));
if (random > currentspeed)
random = currentspeed;
ghostspeed[i] = validspeeds[random];
}
To sum it all up, the code I posted above (particularly the "Line which kills your code") sets ghosty[i] to a negative. It will only do this at odd indexes (ghostx[0], and ghostx[2] will be positive, but [1] (which is the index you have stated having issues with) will be negative.
Later down the line, this bit of code here:
pos = ghostx[i] / blocksize + nrofblocks * (int)(ghosty[i] / blocksize);
uses ghostx[] in a division, causing the whole thing to become negative.
You then, at the line of code you stated to be bad, use screendata[pos], which results in you using a negative index.
EDIT: New answer proposal.
Now, the only lines of code I have found so far that modify ghostx or ghosty are:
ghostx[i] = ghostx[i] + (ghostdx[i] * ghostspeed[i]);
ghosty[i] = ghosty[i] + (ghostdy[i] * ghostspeed[i]);
and
ghosty[i] = 4 * blocksize;
ghostx[i] = 4 * blocksize;
We know the latter of the two can't be it, because blocksize and 4 are both positive.
That means that
ghostx[i] = ghostx[i] + (ghostdx[i] * ghostspeed[i]);
ghosty[i] = ghosty[i] + (ghostdy[i] * ghostspeed[i]);
are the problem.
Looking at this, it appears to me that your ghosts are wandering outside your board! I noticed that ghostdx can be negative (ghostdx being ghost delta x right?) This means that when your ghost is traveling in the negative direction, it ends up going so far that it ends up going outside the board.
Right after those lines, I suggest adding these lines:
if (ghostx[i] < 0) ghostx[i] = 0;
if (ghosty[i] < 0) ghosty[i] = 0;
if (ghostx[i] >= WHATEVER_YOUR_MAX_POSITION_IS) ghostx[i] = WHATEVER_YOUR_MAX_POSITION_IS - 1;
if (ghosty[i] >= WHATEVER_YOUR_MAX_POSITION_IS) ghosty[i] = WHATEVER_YOUR_MAX_POSITION_IS - 1;
See if that fixes your problems please!
pos = pacmanx / blocksize + nrofblocks * (int)(pacmany / blocksize);
make sure your assignd value cannot be > nrofblocks*nrofblocks, also make sure that your divisor is allways > 0, as far as i remember in java you can devide by zero but this will result in NaN , pos[NaN] is obviously out of bounds.. ah but i dont think this makes sense for int , which is your variable pos.
Iam just providing some thoughts i would check first, its too late to crunch the numbers, sorry ;)
Btw, why not use vectors for the coordinates ? should be much easier

java applet game jumping

I'm quite new with Java and at the moment I'm making a super meat boy kinda game but I just can't figure out how to make him jump.
Here is the code I have so far, can anyone please describe me how to make him jump? Thanks.
import java.applet.Applet;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.Timer;
import java.util.TimerTask;
public class meatboy extends Applet implements KeyListener{
public int x = 10, y = 300, gravity = 3;
public int xs = 380, ys = 230;
double jumptime = 0;
public boolean right, left, up, jump, start, grounded;
public void init(){
setSize(800,400);
setBackground(Color.black);
addKeyListener(this);
/////Movement//////
Timer t = new Timer();
t.schedule(new TimerTask(){public void run(){
if (start == true){
if (right == true){
x = x + 3;
}if (left == true){
x = x - 3;
}if(up == true && grounded == true){
while(jumptime < 50){
y--;
jumptime = jumptime + 0.5;
}
grounded = false;
jumptime = 0;
}
/////GRAVITY//////
y = y + gravity;
///////Collision Dectection/////
if(x > 790){//right of screen stop
x = 10;
}if(x < 10){// left stop
x = 789;
}if(y > 352){
y = y - 3;
grounded = true;
}
////////////End of collision///////////
repaint();
}}},10,10);
///////movement end////////
}
public void paint(Graphics g){
////////CREATES MEATBOY///////////////
if (start == false){
x = 10;
y = 300;
g.setColor(Color.DARK_GRAY);
g.fillRect(0, 0, 800, 400);
g.setColor(Color.white);
g.drawString("MeatBoy 4K", 358, 180);
g.drawString("Press Z to start!!!!", 350, 200);
g.setColor(Color.RED);
g.fillRect(xs, ys, 16, 16);//meatboys body
g.fillRect(xs + 16, ys + 6, 4, 4);//arm
g.fillRect(xs - 4, ys + 6, 4, 4);//arm
g.fillRect(xs, ys + 12, 4, 6);//leg
g.fillRect(xs + 12, ys + 12, 4, 6);//leg
g.setColor(Color.black);
g.fillRect(xs + 2, ys + 2, 5, 5);//eye
g.fillRect(xs + 10, ys + 2, 5, 5);//eye
}
if (start == true){
g.setColor(Color.RED);
g.fillRect(x, y, 16, 16);//meatboys body
g.fillRect(x + 16, y + 6, 4, 4);//arm
g.fillRect(x - 4, y + 6, 4, 4);//arm
g.fillRect(x, y + 12, 4, 6);//leg
g.fillRect(x + 12, y + 12, 4, 6);//leg
g.setColor(Color.black);
g.fillRect(x + 2, y + 2, 5, 5);//eye
g.fillRect(x + 10, y + 2, 5, 5);//eye
///////////END OF MEATBOY//////////////////
////////Creates Floor///////////////////
g.setColor(Color.GRAY);
g.fillRect(0, 370, 800, 30);
}
}
/**
*
*/
private static final long serialVersionUID = 1L;
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_Z){
//right = true;
start = true;
}
if (e.getKeyCode() == KeyEvent.VK_RIGHT){
//right = true;
right = true;
}if (e.getKeyCode() == KeyEvent.VK_LEFT){
left = true;
}if (e.getKeyCode() == KeyEvent.VK_UP){
up = true;
}if (e.getKeyCode() == KeyEvent.VK_SPACE){
up = true;
}
}
public void keyReleased(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_RIGHT){
//right = true;
right = false;
}if (e.getKeyCode() == KeyEvent.VK_LEFT){
left = false;
}if (e.getKeyCode() == KeyEvent.VK_UP){
up = false;
}if (e.getKeyCode() == KeyEvent.VK_SPACE){
up = false;
}
}
public void keyTyped(KeyEvent e) {
}
}
When you jump you make a vertical change of 1 (up), however, your gravity makes a vertical change of -3 (down) and if getting too far down you reset the vertical position to ground level.
What you need to do is compensate for gravity when "jumping" and one way of doing it would be to use
while(jumptime < 50){
y -= 1 + gravity;
jumptime = jumptime + 0.5;
}

Categories

Resources