I'm new to coding in Java and I'm trying to code a basic collecting items game but when I tried implementing collision the code the game now just entirely refuses to load and I can't figure out why. No specific code please because it's for a course. It was working before I added the collection function but I cannot work out exactly what broke it. All that the error box says is >NullPointerException. Could not run the sketch (Target VM failed to initialize).
Code
Billy player;
Orb orb1, orb2, orb3, orb4, orb5;
CountDown timer;
int orbscollected=0;
PImage background;
int bgX=0;
final int playing=0;
final int finished=1;
int gamestate=playing;
void setup(){
size(1000, 600);
background=loadImage("background.jpg");
background.resize(width,height);
player=new Billy(height/2);
orb1=new Orb(850, 500);
orb2=new Orb(850, 400);
orb3=new Orb(850, 300);
orb4=new Orb(850, 200);
orb5=new Orb(850, 100);
timer = new CountDown(60);
}
void draw(){
if (gamestate==playing){
image(background, bgX, 0);
player.render();
orb1.render();
orb2.render();
orb3.render();
orb4.render();
orb5.render();
text(timer.getRemainingTime(), 10,10);
if (timer.getRemainingTime() == 0){
gamestate = finished;
}
if (player.collected(orb1)==true && player.collected(orb2)==true && player.collected(orb3)==true && player.collected(orb4)==true && player.collected(orb5)==true){
gamestate = finished;
}
}
}
void keyPressed(){
if (key==CODED){
if (keyCode == UP && player.y > 0)
player.y -=5;
else if (keyCode == DOWN && player.y < height-20)
player.y +=5;
else if (keyCode == RIGHT && player.x < width-20)
player.x +=5;
else if (keyCode == LEFT && player.x >0)
player.x -=5;
}
}
class Billy {
int x = 50 ;
int y;
int counter;
Boolean collected;
PImage img = loadImage("Old_hero.png");
PImage img2 = loadImage("Old_hero2.png");
Billy(int y) {
this.y = y;
}
void render() {
if (counter < 10) {
image(img, x, y);
} else if (counter < 20) {
image(img2, x, y);
} else {
counter = 0;
}
counter++;
}
Boolean collected(Orb orb){
if (player.x == orb.x && player.y == orb.y) {
collected=true;
}
return collected;
}
}
class Orb {
int x;
int y;
int counter;
PImage img1 = loadImage("mm_yellow.png");
Orb(int x, int y){
this.x = x;
this.y = y;
}
void update() {
move();
render();
}
void move() {
x -= (0);
}
void render() {
if (counter>0){
image(img1, x, y);
}
counter++;
}
}
class CountDown
{
private int durationSeconds;
public CountDown(int duration)
{
this.durationSeconds = duration;
}
public int getRemainingTime() //return the seconds left on the timer or 0
{ //millis() processing command, returns time in 1000ths sec since program started
return max(0, durationSeconds - millis()/1000) ;
}
}
Something that sticks out directly is the return value of your collected method.
If the player is not on the orb coordinates then you're returning null and that's most likely where your exception is coming from.
Change the collected variable to a boolean or initialize it to false on creation.
Related
I want this code to effectively increase the smoothness of the transition between directions (it only works with one key at a time) so that I can use multiple keys. The problem is that whenever I change direction the "Player" stops and then continues in the new direction. I want the "Player" to smoothly transition between directions without having to fully release the active key before pressing the new one.
Main code:
Ball ball;
Player player1;
Player player2;
void setup() {
size(1368,768);
frameRate(60);
noStroke();
ball = new Ball(width/2, height/2, 30);
player1 = new Player(0, height/2, 30, 150);
player2 = new Player(width-30, height/2, 30, 150);
ball.speedX = -10;
ball.speedY = random(-5,5);
}
void draw() {
background(0);
ball.display();
ball.move();
player1.run();
player2.run();
//Collision
if (ball.top() < 0) {
ball.speedY = -ball.speedY;
}
if (ball.bottom() > height) {
ball.speedY = -ball.speedY;
}
if (ball.left() < 0) {
ball.speedX = 0;
ball.speedY = 0;
}
if (ball.right() > width) {
ball.speedX = 0;
ball.speedY = 0;
}
}
void keyPressed() {
player1.pressed((key == 'w' || key == 'W'), (key == 's' || key == 'S'));
player2.pressed((keyCode == UP), (keyCode == DOWN));
}
void keyReleased() {
player1.released((key == 'w' || key == 'W'), (key == 's' || key == 'S'));
player2.released((keyCode == UP), (keyCode == DOWN));
}
Player class code:
class Player {
float x, y;
int dy = 0;
float w, h;
float speedY = 5;
color c;
//Constructor
Player(float tempX, float tempY, float tempW, float tempH){
x = tempX;
y = tempY;
w = tempW;
h = tempH;
speedY = 0;
c = (255);
}
void run() {
display();
move();
}
void display() {
fill(c);
rect(x, y-h/2, w, h);
}
void move() {
y += dy * speedY;
}
void pressed(boolean up, boolean down) {
if (up) {dy = -1;}
if (down) {dy = 1;}
}
void released(boolean up, boolean down) {
if (up) {dy = 0;}
if (down) {dy = 0;}
}
}
Thanks in advance!
Add 2 attributes move_up and move_down to the class Player and set the attributes in
pressed respectively released:
class Player {
// [...]
boolean move_up = false, move_down = false;
void pressed(boolean up, boolean down) {
if (up) {move_up = true;}
if (down) {move_down = true;}
}
void released(boolean up, boolean down) {
if (up) {move_up = false;}
if (down) {move_down = false;}
}
}
Change speedY dependent on the attributes in move. Continuously reduce the speed if neither move_up not move_down is set (speedY = speedY * 0.95;). That causes that the player smoothly slows down if no key is pressed. If move_up or move_down is pressed the slightly change the speed dependent on the desired direction. Restrict the speed to a certain interval (speedY = max(-5.0, min(5.0, speedY));):
class Player {
// [...]
void move() {
if (!move_up && !move_down) {speedY *= 0.95;}
if (move_up) {speedY -= 0.1;}
if (move_down) {speedY += 0.1;}
speedY = max(-5.0, min(5.0, speedY));
y += speedY;
}
// [...]
}
Class Player:
class Player {
float x, y;
float w, h;
float speedY = 0.0;
color c;
boolean move_up = false, move_down = false;
//Constructor
Player(float tempX, float tempY, float tempW, float tempH){
x = tempX;
y = tempY;
w = tempW;
h = tempH;
c = (255);
}
void run() {
display();
move();
}
void display() {
fill(c);
rect(x, y-h/2, w, h);
println(y);
}
void move() {
if (!move_up && !move_down) {speedY *= 0.95;}
if (move_up) {speedY -= 0.1;}
if (move_down) {speedY += 0.1;}
speedY = max(-5.0, min(5.0, speedY));
y += speedY;
}
void pressed(boolean up, boolean down) {
if (up) {move_up = true;}
if (down) {move_down = true;}
}
void released(boolean up, boolean down) {
if (up) {move_up = false;}
if (down) {move_down = false;}
}
}
If you want smooth transitions, you're going to have to give up "adding a fixed integer distance" in the key handlers, and instead track which keys are down or not, and then accelerating/decelerating your player every time draw() runs. As simple illustration:
Box box;
boolean[] active = new boolean[256];
void setup() {
size(500,500);
box = new Box(width/2, height/2);
}
void draw() {
pushStyle();
background(0);
box.update(active); // First, make the box update its velocity,
box.draw(); // then, tell the box to draw itself.
popStyle();
}
void keyPressed() { active[keyCode] = true; }
void keyReleased() { active[keyCode] = false; }
With a simple box class:
class Box {
final float MAX_SPEED = 1, ACCELERATION = 0.1, DECELERATION = 0.5;
float x, y;
float dx=0, dy=0;
Box(float _x, float _y) { x=_x; y=_y; }
void draw() {
// We first update our position, based on current speed,
x += dx;
y += dy;
// and then we draw ourselves.
noStroke();
fill(255);
rect(x,y,30,30);
}
void update(boolean[] keys) {
if (keys[38]) { dy -= ACCELERATION ; }
else if (keys[40]) { dy += ACCELERATION ; }
else { dy *= DECELERATION; }
if (keys[37]) { dx -= ACCELERATION ; }
else if (keys[39]) { dx += ACCELERATION ; }
else { dx *= DECELERATION; }
dx = constrain(dx, -MAX_SPEED, MAX_SPEED);
dy = constrain(dy, -MAX_SPEED, MAX_SPEED);
}
}
The important part here is the update code, which updates the box's x and y velocity such that if a directional key is currently pressed, we increase the speeed (dx/dy) in that direction. Importantly, if no keys are pressed we also dampen the speed to that it returns to 0.
Finally, to make sure we don't end up with infinite speed, we cap the maximum allowed velocity.
Hi basically whenever I click p or b to run one of my games they run, but you can't see them as they don't draw over the main menu screen. These games do work if separated.
PImage pongImage, brickImage;
boolean mouseDown = false;
boolean [] keys = new boolean [128];
Ball ball;
Paddleb gamerPaddle;
static ArrayList<Brick> bricks = new ArrayList();
Puck puck;
Paddle one;//left
Paddle two;//right
int oneScore = 0;
int twoScore = 0;
int gameScreen = 0;
void setup() {
fullScreen();
ball = new Ball();//creating objects
gamerPaddle = new Paddleb();
puck = new Puck();//creating objects
one = new Paddle(true);
two = new Paddle(false);
}
void draw() {
menuPress();
if (gameScreen == 0) {
mainMenu();
}
if (gameScreen ==1) {
gamePong();
}
if (gameScreen == 2) {
gameBrick();
}
}
void keyReleased() {
keys[key] = false;
one.move(0);
two.move(0);
gamerPaddle.move(0);
}
void menuPress() {
if (keys['p'] == true) {
gameScreen = 1;
} else if (keys ['b'] == true) {
gameScreen =2;
} else {
gameScreen = 0;
}
}
void moves() {
if (keys['w'] == true) {
one.move(-10);
} else if (keys['s'] == true) {
one.move(10);
}
if (keys['i'] == true) {
two.move(-10);
} else if (keys['k'] == true) {
two.move(10);
}
if (keys['a'] == true) {
gamerPaddle.move(-10);
} else if (keys['d'] == true) {
gamerPaddle.move(10);
}
}
void keyPressed() {
keys[key] = true;
}
void drawBricks() {
for (int i = 0; i <= bricks.size() - 1; i++) {
fill(255);
rectMode(CORNER);
rect(bricks.get(i).x, bricks.get(i).y, bricks.get(i).s, bricks.get(i).s2);
}
}
void bricksSetup() {
rectMode(CORNER);
float s = 80;
float x = width/4;
float y = Brick.space;
while (y < height/2) {
while (x < width - width/4) {
bricks.add(new Brick(x, y, s, s));
x +=90;
}
x = width/4;
y +=90;
}
}
void mainMenu() {
float picsY = height/2;
float brickX = 2 * width/3;
float pongX = width/3 - width/4;
pongImage = loadImage("pong photo.PNG");
brickImage = loadImage("Brick breaker.PNG");
pongImage.resize(width/4, height/4);
brickImage.resize(width/4, height/4);
background(150);
fill(255);
textSize(72);
text("AhMen's Arcade", width/5 + width/7, height/3);
image(pongImage, pongX, picsY);
text("Pong", width/6, 4 * height/5 + height/50);
image(brickImage, brickX, picsY);
text("Brick Breaker", 2 * width/3 + width/100, 4 * height/5 + height/50);
}
void gamePong() {
background(0);
System.out.println("cat");
boolean gameEnding = false;
do {
background(0);
one.screen();//creates paddle
two.screen();
puck.position();
puck.sides();
puck.screen();
moves();
puck.checkHitOne(one);
puck.checkHitTwo(two);
one.refresh();//limits y movement and keeps it moving at speed of 0 to make stops and starts not noticible
two.refresh();
fill(255);
textSize(32);
text(oneScore, 20, 50);
text(twoScore, width-40, 50);
textMode(CENTER);
text("PONG", width/2-55, 50);
} while (gameEnding != true);
exit();
}
void gameBrick() {
System.out.println("ya");
background(0);
bricksSetup();
ball.position();
while (ball.y - ball.r > height || ball.p1Score >= ((bricks.size()-1)*50)) {
System.out.println('l');
background(0);
moves();
drawBricks();
ball.checkHitTwo(gamerPaddle);
ball.checkHitBrick();
gamerPaddle.screen();//creates paddle
gamerPaddle.refresh();//limits y movement and keeps it moving at speed of 0 to make stops and starts not noticible
gamerPaddle.refresh();
ball.position();
ball.sides();
ball.screen();
ball.score();
}
exit();
}
this is just the main method btw, I do have other methods for the objects. I am not sure why this doesn't work, but if someone that has an Idea what the issue may be please lmk.
The processing draw function does not run on a seperate thread. When you have a while loop, which doesn't end, the draw-function never gets executed anymore.
You have to use variables scoped to the processing file and not just a function and then modify those variables inside the functions you currently use as the game-loops.
For example, if you want a program where a ball moves to the right and returns to coordinate 0 after passing it, you would have to structure it like this:
Ball ball = new Ball();
void draw() {
playBallGame();
drawBall();
}
void playBallGame() {
if (ball.x > width) ball.x = 0;
ball.x++;
}
Not like this:
void draw() {
drawBall();
playBallGame();
}
void playBallGame() {
Ball ball = new Ball();
while (true) {
if (ball.x > width) ball.x = 0;
ball.x++;
}
}
I can draw lines, but the thickness is constant. I need to change the thickness when I press a button. In this example pressing 'w' will increase the thickness and pressing 'q' will decrease the thickness.
import java.awt.*;
import java.applet.*;
import sun.swing.SwingUtilities2;
public class draw extends Applet {
boolean isBlack = true;
Point startPoint;
Point points[];
int numPoints;
boolean drawing;
int n = 0;
#Override
public void init() {
startPoint = new Point(0, 0);
points = new Point[10000];
drawing = false;
resize(300, 400);
}
#Override
public void paint(Graphics g) {
if (n == 0) {
g.setColor(Color.red);
}
if (n == 1) {
g.setColor(Color.green);
}
if (n == 2) {
g.setColor(Color.blue);
}
if (n == 3) {
g.setColor(Color.black);
}
int oldX = startPoint.x;
int oldY = startPoint.y;
for (int i = 0; i < numPoints; ++i) {
g.drawLine(oldX, oldY, points[i].x, points[i].y);
oldX = points[i].x;
oldY = points[i].y;
}
}
#Override
public boolean keyDown(Event evt, int key) {
char keyChar = (char) key;
if (keyChar == 'w') {
n++;
if (n > 3) {
n = 0;
}
}
if (keyChar == 'q') {
n--;
if (n < 0) {
n = 3;
}
}
return true;
}
#Override
public boolean mouseDown(Event evt, int x, int y) {
if (!drawing) {
startPoint.x = x;
startPoint.y = y;
}
drawing = !drawing;
return true;
}
#Override
public boolean mouseMove(Event evt, int x, int y) {
if ((drawing) && (numPoints < 10000)) {
points[numPoints] = new Point(x, y);
++numPoints;
repaint();
}
return true;
}
}
But I can't calculate the thickness of the line, how would I do that?
You need to use the Graphics2D package:
Graphics2D g2 = SwingUtilities2.getGraphics2D(g);
g2.setStroke(new BasicStroke(n));
g2.drawLine(oldX, oldY, points[i].x, points[i].y);
I think that's is all you need. It's been awhile since I've worked with it.
I am designing a simple java 2d game.where an aircraft shoots missiles and they hit alien ships.(pictures are attached for a better understanding).
Now I need to detect when the missile hits the alien ship. So as to count the number of total hits. I used the rectangle1.intersects(rec2)method, but instead of giving me an integer 1 as the answer (after the boolean of course) it gives me some funny answer. I guess like how much the two rectangles intersect...
Also when adding new aliens in an arraylist I use the following: I add new aliens every two seconds, but this slows down the game very much.
So please guide me on these two issues.
There is a game class (contains the main frame), board class (the panel on which I draw) alient, missile and craft class. Below I am giving the the actionPerformed() of the panel class which gets called by a timer every 2ms (the rest of the code is below).
///CODE TO BE FOCUSED ON
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import javax.swing.*;
public class game extends JFrame {
static long z;
game()
{
add(new board());
setBounds(0, 0, 500, 500);
setVisible(true);
setLayout(null);
setLocationRelativeTo(null);
setTitle("\t\t...................::::~~~~'S GAME~~~~:::::...............");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new game();
z = System.currentTimeMillis();
}
}
class board extends JPanel implements ActionListener
{
Timer t = new Timer(5, this);
public ArrayList alien_list;
craft craft_list = new craft();
Label l = new Label();
int total_hits = 0;
public board() {
setFocusable(true);
setLayout(null);
setDoubleBuffered(true);
setBackground(Color.BLACK);
addKeyListener(craft_list);
l.setBounds(0, 0, 150, 30);
l.setBackground(Color.GREEN);
add(l);
t.start();
alien_list = new ArrayList();
alien_list.add(new alien(0, 100));
alien_list.add(new alien(0, 150));
alien_list.add(new alien(0, 200));
}
public void paint(Graphics g) {
super.paint(g);
Graphics2D g1 = (Graphics2D) g;
long z = (System.currentTimeMillis() - game.z) / 1000;
if (z >= 60)
{
remove(l);
g.setColor(Color.red);
g1.drawString("time up", 100, 100);
} else
{
g1.drawImage(craft_list.getImage(), craft_list.getX(),
craft_list.getY(), null);
ArrayList a = craft_list.getmissile();
for (int i = 0; i < a.size(); i++) {
missile m = (missile) a.get(i);
g1.drawImage(m.getImage(), m.getX(), m.getY(), null);
}
l.setText("time elapsed:" + " " + +z + " " + "hits:" + " "
+ total_hits);
for (int i = 0; i < alien_list.size(); i++) {
alien m = (alien) alien_list.get(i);
g1.drawImage(m.getImage(), m.getX(), m.getY(), null);
}
}
}
public void actionPerformed(ActionEvent e) {
ArrayList a = craft_list.getmissile();
for (int i = 0; i < a.size(); i++) {
missile m = (missile) a.get(i);
if (m.visible == true)
m.move();
else
a.remove(i);
}
long z = (System.currentTimeMillis() - game.z) / 1000;
if (z % 3 == 0)
alien_list.add(new alien(-10, 100));
for (int j = 0; j < alien_list.size(); j++) {
alien m = (alien) alien_list.get(j);
if (m.visible == true)
m.move();
else
alien_list.remove(j);
}
craft_list.move();
collison();
repaint();
}
public void collison() {
ArrayList a = craft_list.getmissile();
for (int i = 0; i < a.size(); i++) {
missile m = (missile) a.get(i);
Rectangle r1 = m.getBounds();
for (int j = 0; j < alien_list.size(); j++) {
alien l = (alien) alien_list.get(j);
Rectangle r2 = l.getBounds();
if (r1.intersects(r2)) {
total_hits++;
m.setVisible(false);
l.setVisible(false);
}
}
}
}
}
class craft extends KeyAdapter
{
int x = 250;
int y = 400;
ArrayList m = new ArrayList();
Image i;
int dx, dy;
craft() {
ImageIcon i1 = new ImageIcon("1a.jpg");
i = i1.getImage();
}
public Image getImage() {
return i;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public void move() {
x += dx;
y += dy;
if (x < 0)
x = 0;
if (x > 450)
x = 450;
if (y > 420)
y = 420;
if (y < 200)
y = 200;
}
public void keyPressed(KeyEvent k)
{
int key = k.getKeyCode();
if (key == KeyEvent.VK_SPACE) {
fire();
}
if (key == KeyEvent.VK_LEFT) {
dx = -1;
}
if (key == KeyEvent.VK_RIGHT) {
dx = 1;
}
if (key == KeyEvent.VK_UP) {
dy = -1;
}
if (key == KeyEvent.VK_DOWN) {
dy = 1;
}
}
public void keyReleased(KeyEvent e) {
int key = e.getKeyCode();
if (key == KeyEvent.VK_LEFT) {
dx = 0;
}
if (key == KeyEvent.VK_RIGHT) {
dx = 0;
}
if (key == KeyEvent.VK_UP) {
dy = 0;
}
if (key == KeyEvent.VK_DOWN) {
dy = 0;
}
}
public void fire() {
m.add(new missile(getX() + 13, getY() - 6));
}
public ArrayList getmissile() {
return m;
}
public Rectangle getBounds() {
return new Rectangle(x, y, i.getWidth(null), i.getHeight(null));
}
}
class missile {
Image i;
int x, y;
public boolean visible;
missile(int x, int y) {
this.x = x;
this.y = y;
visible = true;
ImageIcon i1 = new ImageIcon("1c.jpg");
i = i1.getImage();
}
public Image getImage() {
return i;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public void move() {
y--;
if (y < 0)
visible = false;
}
public Rectangle getBounds() {
return new Rectangle(x, y, i.getWidth(null), i.getHeight(null));
}
public void setVisible(boolean t) {
this.visible = t;
}
}
class alien {
Image i;
int x, y;;
public boolean visible;
public alien(int x, int y)
{
this.x = x;
this.y = y;
ImageIcon i1 = new ImageIcon("b.jpg");
i = i1.getImage();
visible = true;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public Image getImage() {
return i;
}
public void move() {
x++;
if (x > 500)
visible = false;
}
public Rectangle getBounds() {
return new Rectangle(x, y, i.getWidth(null), i.getHeight(null));
}
public void setVisible(boolean t) {
this.visible = t;
}
}
Ok, your code format is kind of unreadable and invites everybody to oversee otherwise obvious bugs. That is what I have seen so far for your performance issue:
getBounds() creates a new Rectangle instance every time it gets called. You should update the bounds rectangle at the last line of your move() and just return the rectangle instance instead of creating a new one.
Reuse Image or ImageIcon objects. There is no need to load the same jpg file over and over again in a constructor. Make it static or use a image cache.
Instead of o++ in fire() you should use o = m.size(). Mainly because you never call o--, you only remove the rocket from the ArrayList.
And at that point everybody loses track of what o and m means. Name your variables better! o should be amountOfRockets and m should be listOfRockets.
When you use Eclipse, press ctrl + shift + f to format the code which I highly recommend. After that go through your code and name the variables correctly. That means you should give them a descriptive name. And finally: let the name of your classes start with an upper case.
Very likely that this will not yet remove all issues but it will at least help us to understand and read your code easier... which might lead us to a solution...
Update:
You still haven't done 1. and 2. I suggested but you did 3.
Here is what 1. should be as a sample for the Alien class:
private Rectangle bounds
//constructor
Alien() {
// your stuff and the bounds:
bounds = new Rectangle(x, y, i.getWidth(null), i.getHeight(null));
}
public void move() {
bounds.x++;
if (bounds.x > 500)
visible = false;
}
public Rectangle getBounds() {
return bounds;
}
You need to implement that for the Rocket class as well.
What I still don't get is where you remove the old Alien objects. Just setting their visibility is not enough. You should remove them from the list of your Alien objects. Otherwise you will loop through objects that are not there anymore.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I am trying to make a prototype for a game i have to make for school. But it isnt going great. My question is how can i import a variable from one class to another? I want the playerX and Y variable so i can check collision. This is written in Processing (Java).
If there's a better way of checking collision please tell me :) im out of ideas. Thanks in advance!
My code:
Main class
Player thePlayer = new Player();
Guard theGuard = new Guard();
SpeedPWRUP speedPowerUp = new SpeedPWRUP();
void setup() {
size(1000, 500);
theGuard.init();
thePlayer.init();
speedPowerUp.init();
}
void updateGame() {
theGuard.update();
thePlayer.update();
speedPowerUp.update();
}
void drawGame() {
thePlayer.draw();
theGuard.draw();
speedPowerUp.draw();
fill(color(255, 255, 255));
text("Score:", 10, 20);
}
void draw() {
background(255);
fill (0, 0, 0);
rect(-10, 401, 1100, 100);
noFill();
updateGame();
drawGame();
}
Guard class
class Guard {
public float guardX, guardY;
float guardVX, guardVY;
int fillColor;
float guardHeight, guardWidth;
void init() {
guardHeight = 80;
guardWidth = 40;
guardX = 300;
guardY = 400-guardHeight;
fillColor = color(255,0,0);
}
void update() {
if (guardX == (random(width)-100))
guardVX = 3;
if (guardX == (random(width)+100))
guardVX = -3;
guardX += guardVX;
guardY += guardVY;
}
void draw() {
fill(fillColor);
rect(guardX, guardY, guardWidth, guardHeight);
noFill();
}
}
Player class
class Player {
public float playerX, playerY;
float vx, vy;
int fillColor;
float playerHeight, playerWidth;
float jumpTime;
float jumpHeight;
boolean isJumping;
void init() {
playerHeight = 80;
playerWidth = 40;
fillColor = color(0, 0, 0);
jumpTime = 200;
jumpHeight = 100;
isJumping = false;
playerX = 100;
playerY = 400-playerHeight;
vx = 0;
vy = 0;
}
void update() {
if (keyPressed) {
if (key == 'a' || key == 'A') {
vx = -2;
}
} else {
vx = 0;
}
if (keyPressed) {
if (key == 'd' || key == 'D') {
vx = 2;
}
} else {
vx = 0;
}
if (keyPressed) {
if ((key == 'w' || key == 'W') && ( playerY > 400 - jumpHeight)) {
isJumping = true;
}
} else {
isJumping = false;
}
if (playerY < 400 - jumpHeight) {
}
if (keyPressed) {
if (key == 's' || key == 'S') {
playerHeight = 40;
}
} else {
playerHeight = 80;
}
if(isJumping == true) {
vy = -15;
} else {
vy = 0;
}
if (playerY < (400-playerHeight)) {
vy = vy + 2.5;
}
playerX += vx;
playerY += vy;
}
void draw() {
fill(fillColor);
rect(playerX, playerY, playerWidth, playerHeight);
noFill();
}
}
Speed power up class
class SpeedPWRUP {
float diameter;
public float pwrUpX, pwrUpY;
int fillColor;
void init() {
diameter = 40;
pwrUpX = 100;
pwrUpY = 100;
fillColor = color(0, 0, 255);
}
void update() {
if (((playerX>pwrUpX) && (playerX < pwrUpX+diameter)) && (playerY > pwrUpY)&&(playerY>pwrUpY+diameter))
end();
}
void draw() {
fill(fillColor);
ellipse(pwrUpX, pwrUpY, diameter, diameter);
noFill();
}
}
To check collision:
You can define a static object in your main CLASS:
/* global static values */
public static Player thePlayer = new Player();
or list of players
public static ArrayList<Player> Players = new ArrayList<>();
You can use Getter functions in the Player class.
For instance:
public float getPlayerX(){
return playerX;
}