Move object in simple Java BigBang World - java

I am attempting to create a Big Bang world which contains a circle whose initial state should have it moving one pixel diagonally to the bottom-right. Every time the user presses the four arrow keys, the circle should move one pixel towards that direction and keep moving. For example, if I keep pressing the right arrow key, the circle should move towards the right and keep moving faster and faster each time I press it. The problem I am having is that I can't get the circle to move at all! I thought changing x and y coordinates oft he circle for each method should move it accordingly. What am I doing wrong? What can I do to have the circle move as I have described it? Here is the file Game.java that I need to fix:
import java.awt.*;
import java.awt.event.*;
import java.util.*;
public class Game implements World {
public Game() { }
int x, y = 200;
int width, height = 100;
void Circle(int x, int y, int width, int height){
this.x = x;
this.y = y;
this.width = width;
this.height = height;
}
public void draw(Graphics g) {
int x = 200;
int y = 200;
int width = 100;
int height = 100;
g.setColor(Color.red);
g.fillOval(x,
y,
width,
height);
}
public void teh() {
this.x++;
this.y++;
}
public void meh(MouseEvent e) {
int x = e.getX(), y = e.getY();
System.out.println("Mouse event detected.");
}
public void keh(KeyEvent e) {
int x = e.getKeyLocation(), y = e.getKeyLocation();
int key = e.getKeyCode();
if (key == KeyEvent.VK_UP){
this.y--;
System.out.println("Up.");
}
else if (key == KeyEvent.VK_DOWN){
this.y++;
System.out.println("Down.");
}
else if (key == KeyEvent.VK_RIGHT){
this.x++;
System.out.println("Right.");
}
else if (key == KeyEvent.VK_LEFT){
this.x--;
System.out.println("Left.");
}
else{}
// switch( keyCode ) {
// case KeyEvent.VK_UP:
// // handle up
// break;
// case KeyEvent.VK_DOWN:
// // handle down
// break;
// case KeyEvent.VK_LEFT:
// // handle left
// break;
// case KeyEvent.VK_RIGHT :
// // handle right
// break;
// }
}
public boolean hasEnded() {
return false;
}
public void sayBye() {
System.out.println("BYE!");
}
public static void main(String[] args) {
BigBang b = new BigBang(new Game());
b.start( 50, // delay
400 // size
);
}
}
These are the supplementary files that are used but should remain untouched. I am including them for your reference:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class BigBang extends JComponent implements ActionListener, MouseListener, MouseMotionListener, KeyListener {
Timer timer;
World world;
public BigBang(World world) {
this.world = world;
this.addMouseListener(this);
this.addMouseMotionListener(this);
this.addKeyListener(this);
this.setFocusable(true);
this.requestFocus();
}
public void start(int delay, int size) {
JFrame a = new JFrame();
a.add( this );
a.setVisible(true);
a.setSize(size, size);
this.timer = new Timer(delay, this);
this.timer.start();
}
public void mouseEntered(MouseEvent e) { }
public void mouseExited(MouseEvent e) { }
public void mousePressed(MouseEvent e) {
this.world.meh(e);
this.repaint();
}
public void mouseDragged(MouseEvent e) {
this.world.meh(e);
this.repaint();
}
public void mouseMoved(MouseEvent e) { }
public void mouseReleased(MouseEvent u) {
this.world.meh(u);
this.repaint();
}
public void mouseClicked(MouseEvent e) { }
public void keyPressed(KeyEvent e) {
this.world.keh(e);
this.repaint();
}
public void keyReleased(KeyEvent e) { }
public void keyTyped(KeyEvent e) { }
// int count;
public void actionPerformed(ActionEvent e) {
// this.count += 1;
// System.out.println("Ouch" + this.count);
if (this.world.hasEnded()) {
this.timer.stop();
this.world.sayBye();
} else {
this.world.teh();
}
this.repaint();
}
public void paintComponent(Graphics g) {
this.world.draw(g);
}
}
And the interface World.java:
import java.awt.Graphics;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
interface World {
void draw(Graphics g);
void teh();
void meh(MouseEvent e);
void keh(KeyEvent e);
boolean hasEnded();
void sayBye();
}
Where does my mistake lie? Why am I not able to move the circle when the arrow keys are pressed? How can I continue to add on to the velocity of the object each time the arrow key is pressed? Any modifications or advice will be helpful.

The issue is in your draw method:
public void draw(Graphics g)
{
int x = 200;
int y = 200;
int width = 100;
int height = 100;
g.setColor(Color.red);
g.fillOval(x, y, width, height);
}
You are constantly making new local variables, x, y, width, and height, and drawing with those
Instead you should be using the variables your class already has designed:
public void draw(Graphics g)
{
g.setColor(Color.red);
g.fillOval(x, y, width, height);
}

Related

Collision detection only working on top side of wall - Java

I have an assignment to create a 2D game, this game must use an abstract class Shape which is used to draw shapes. I decided to make a 2D platformer, but it's my first time doing something like this. I am trying to implement collision detection, and decided to create an offset of my player object to see if it collides with my rectangle object, and stop movement if it does. This is only working for the top side, however on the right, left and botton the player will move through the rectangle and I don't understand why. I expected the collision detection to work for all sides. I would like to know how I can change my collision detection to work for all sides of the rectangle.
Here's a gif showing what happens:
My App class:
package A2;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.geom.Rectangle2D;
import java.util.TreeSet;
import static java.awt.event.KeyEvent.*;
public class App extends JFrame {
private static final int GRAVITY = 10;
private static final int MAX_FALL_SPEED = 30;
public App() {
final Player player = new Player(200, 300);
final Rectangle rectangle = new Rectangle(100, 400);
JPanel mainPanel = new JPanel() {
public void paintComponent(Graphics g) {
super.paintComponent(g);
player.draw(g);
rectangle.draw(g);
}
};
mainPanel.addKeyListener(new controlHandler(this, player, rectangle));
mainPanel.setFocusable(true);
add(mainPanel);
setLayout(new GridLayout());
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setSize(600, 600);
}
class controlHandler implements ActionListener, KeyListener {
int keyCode;
App app;
Player player;
Rectangle rectangle;
TreeSet<Integer> keys = new TreeSet<>();
Timer time = new Timer(5, this);
boolean collision = false;
public controlHandler(App app, Player player, Rectangle rectangle) {
this.app = app;
this.player = player;
this.rectangle = rectangle;
time.start();
}
public void actionPerformed(ActionEvent e) {
player.x += player.xVelocity;
player.y += player.yVelocity;
Rectangle2D offset = player.getOffsetBounds();
if(offset.intersects(this.rectangle.wallObj.getBounds2D())){
collision = true;
player.xVelocity = 0;
player.yVelocity = 0;
}
else collision = false;
repaint();
}
public void keyPressed(KeyEvent e) {
keyCode = e.getKeyCode();
keys.add(keyCode);
switch (keyCode) {
case VK_UP:
moveUp();
break;
case VK_DOWN:
moveDown();
break;
case VK_LEFT:
moveLeft();
break;
case VK_RIGHT:
moveRight();
break;
}
}
public void keyReleased(KeyEvent e) {
released();
}
public void keyTyped(KeyEvent e) { }
public void moveUp() {
player.xVelocity = 0;
player.yVelocity = -2;
}
public void moveDown() {
if(!collision) {
player.xVelocity = 0;
player.yVelocity = 2;
}
}
public void moveLeft() {
player.xVelocity = -2;
player.yVelocity = 0;
}
public void moveRight() {
player.xVelocity = 2;
player.yVelocity = 0;
}
public void released() {
player.xVelocity = 0;
player.yVelocity = 0;
}
}
public static void main(String[] args) {
App app = new App();
app.setVisible(true);
}
}
abstract class Shape {
public double x;
public double y;
public void draw(Graphics g) { }
}
Player class:
package A2;
import java.awt.*;
import java.awt.geom.Rectangle2D;
public class Player extends Shape {
public double xVelocity;
public double yVelocity;
public double length = 60;
public double top;
public double right;
public double left;
public double bottom;
public Rectangle2D playerObj;
public Player(double x, double y) {
this.x = x;
this.y = y;
playerObj = new Rectangle2D.Double(x, y, length, length);
}
public Rectangle2D getOffsetBounds(){
return new Rectangle2D.Double(x + xVelocity , y + yVelocity , length, length);
}
public void draw(Graphics g) {
playerObj = new Rectangle2D.Double(x, y, length, length);
g.setColor(Color.BLACK);
Graphics2D g2 = (Graphics2D)g;
g2.fill(playerObj);
}
}
Rectangle class (will be a platform):
package A2;
import java.awt.*;
import java.awt.geom.Rectangle2D;
public class Rectangle extends Shape {
public double width = 400;
public double height = 30;
public double top;
public double right;
public double left;
public double bottom;
public Rectangle2D wallObj;
public Rectangle(double x, double y) {
this.x = x;
this.y = y;
wallObj = new Rectangle2D.Double(x, y, width, height);
}
public void draw(Graphics g) {
g.setColor(Color.ORANGE);
Graphics2D g2 = (Graphics2D)g;
g2.fill(wallObj);
}
}
So, based on my understanding, your collision detection process is basically to create a "virtual" instance of the object and determine if it will collide.
Your code is actually work, you can tell by the fact that the object "stops" moving once it collides, but what you're not doing, is reseting the objects position after it.
Let's look at the original code...
public void actionPerformed(ActionEvent e) {
player.x += player.xVelocity;
player.y += player.yVelocity;
Rectangle2D offset = player.getOffsetBounds();
if (offset.intersects(this.rectangle.wallObj.getBounds2D())) {
collision = true;
player.xVelocity = 0;
player.yVelocity = 0;
} else {
collision = false;
}
repaint();
}
Update the position of the object
Create a virtual instance of the object, which applies the velocity to the objects current position ... again?
Determine if the object collides
Stop the movement if any
... where do you reset the position of object so it's no longer colliding?!?
Instead, you shouldn't set the position of the object until AFTER you've determine if a collision has occurred or not, for example...
public void actionPerformed(ActionEvent e) {
Rectangle2D offset = player.getOffsetBounds();
if (offset.intersects(this.rectangle.wallObj.getBounds2D())) {
collision = true;
player.xVelocity = 0;
player.yVelocity = 0;
} else {
player.x += player.xVelocity;
player.y += player.yVelocity;
collision = false;
}
repaint();
}
The problem with this approach, though, is if the velocity is large enough, the object will appear not to collide, but stop a little before it, as the amount of change is larger than the remaining gap.
What you need to do, is once you've detected a collision is calculate the difference between the amount you want to move and the space available and move the object only by that amount instead

Java swing keyPressed not working

I'm making Arkanoid game in Java Swing. When I run my game KeyEvent not working.
Why is the game not detecting key events?
Main class in my program make a frame (JFrame). Also I have Manage class which managing all classes from my game.
This is the code: Player class is class of paddle in my game.
//imports
public class Player extends JPanel implements ActionListener, KeyListener
{
private int x, y, width, height;
private Timer timer;
private int fps = 60;
private int delay = 1000/fps;
public Player(int x, int y, int width, int height)
{
//setFocusable(true);
addKeyListener(this);
this.x = x;
this.y = y;
this.width = width;
this.height = height;
timer = new Timer(delay, this);
timer.start();
}
#Override
public void actionPerformed(ActionEvent e)
{
timer.start();
repaint();
}
#Override
public void keyPressed(KeyEvent e)
{
switch (e.getKeyCode())
{
case KeyEvent.VK_A:
if (x <= 0) {
x = 0;
} else {
x -= 3;
}
break;
case KeyEvent.VK_D:
if (x >= 600) {
x = 600;
} else {
x += 3;
}
break;
}
}
public void paint(Graphics g)
{
g.setColor(Color.BLUE);
g.fillRect(x, y, width, height);
}
#Override
public void keyTyped(KeyEvent e) { }
#Override
public void keyReleased(KeyEvent e) { }
}
The main problem with that code was that the custom painted component was neither focusable nor focused (so could not receive key events).
This code fixes those problems as well as a couple more (check code comments for details).
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Player extends JPanel implements ActionListener, KeyListener {
private int x, y, width, height;
private final Timer timer;
private final int fps = 60;
private final int delay = 1000 / fps;
public Player(int x, int y, int width, int height) {
addKeyListener(this);
this.x = x;
this.y = y;
this.width = width;
this.height = height;
timer = new Timer(delay, this);
timer.start();
// a component must be focusable to get key events!
setFocusable(true);
}
#Override
public void actionPerformed(ActionEvent e) {
//timer.start(); // Timer should already be started!
repaint();
}
#Override
// correct method for custom painting a JComponent is paintComponent!
public void paintComponent(Graphics g) {
// call the super method to ensure previous paints are erased!
super.paintComponent(g);
g.setColor(Color.BLUE);
g.fillRect(x, y, width, height);
}
#Override
// a custom painted component should suggest a size to be used by the
// layout manager
public Dimension getPreferredSize() {
return new Dimension(400,100);
}
#Override
public void keyPressed(KeyEvent e) {
switch (e.getKeyCode()) {
case KeyEvent.VK_A:
if (x <= 0) {
x = 0;
} else {
x -= 3;
}
break;
case KeyEvent.VK_D:
if (x >= 600) {
x = 600;
} else {
x += 3;
}
break;
}
}
#Override
public void keyTyped(KeyEvent e) {
}
#Override
public void keyReleased(KeyEvent e) {
}
public static void main(String[] args) {
Runnable r = () -> {
JFrame f = new JFrame(o.getClass().getSimpleName());
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setLocationByPlatform(true);
Player player = new Player(2, 2, 5, 20);
f.setContentPane(player);
f.pack();
f.setMinimumSize(f.getSize());
f.setVisible(true);
// a component must be focused to detect key events!
player.requestFocusInWindow();
};
SwingUtilities.invokeLater(r);
}
}

Why won't my KeyPressed method run

I am trying to write a game in which a character moves around and jumps from block to block in order to get to the end. But the problem I'm facing is that my KeyPressed method won't run. I've tried putting a System.out.println("Hi"); in the method to see if it even starts running. But the "Hi" never showed up. This is my code.
import java.applet.Applet;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
public class Driver extends Applet implements KeyListener
{
private int X = 0;
private int Y = 250;
private int sizeX = 25;
private int sizeY = 25;
private boolean start=false;
public int getX()
{
return X;
}
public void setX(int x)
{
X = x;
}
public int getY()
{
return Y;
}
public void setY(int y)
{
Y = y;
}
public int getsizeY()
{
return sizeY;
}
public void setsizeY(int sizey)
{
sizeY = sizey;
}
public int getsizeX()
{
return sizeX;
}
public void setsizeX(int sizex)
{
sizeX = sizex;
}
public void init()
{
this.addKeyListener(this);
setSize(300, 300);
setFocusable(false);
requestFocus();
}
public void paint(Graphics g)
{
init();
map map1 = new map();
g.setColor(Color.WHITE);
g.fillRect(0, 0, 300, 300);
g.setColor(Color.black);
map1.paint(g);
g.fillRect(X, Y, sizeX, sizeY);
start=true;
}
public void keyTyped(KeyEvent e)
{
}
public void keyReleased(KeyEvent e)
{
}
public void keyPressed(KeyEvent e)
{
if(start)
{
System.out.println("Hi");
if(e.getKeyChar() == 'w')
{
System.out.println("Hi");
setY(getY()-1);
}
if(e.getKeyChar() == 'd')
{
setX(getX()+1);
}
if(e.getKeyChar() == 'a')
{
setX(getX()-1);
}
if(e.getKeyChar() == 's')
{
setY(getY()+1);
}
repaint();
}
}
}
I am still learning how to code so please don't be mean, but if you could help that would be great!

bullets creation in a simple game

I am creating a simple game where shapes fall and the player shoots them, but I am having problems creating bullet at every click of the mouse. I have tried various logic with no help, so am just going to put the code up here so you guys can take a look at it and help me out.
The bullet I created is not been created on every click just one is created and it moves on every click which is wrong........I want one bullet to be created per click.
// My main class: mousework2
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
import java.util.*;
import java.awt.geom.*;
public class mousework2 extends JFrame
{
public static int Width = 300;
public static int Height = 400;
private JPanel p1;
private Image pixMage,gunMage;
public mousework2()
{
super("shoot-em-up");
this.setSize(Width, Height);
this.setResizable(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Dimension pos = Toolkit.getDefaultToolkit().getScreenSize();
int x = (pos.width - Width) / 2;
int y = (pos.height - Height) / 2;
this.setLocation(x, y);
p1 = new CreateImage();
this.add(p1);
this.getContentPane();
Thread t = new recMove(this);
t.start();
}
class recMove extends Thread
{
JFrame b;
public recMove(JFrame b)
{
this.b = b;
}
public void run()
{
while (true) {
b.repaint();
try {
Thread.sleep(50);
} catch (InterruptedException e) {
}
}
}
}
class CreateImage extends JPanel implements MouseListener
{
ArrayList<fallShape> rect = new ArrayList<fallShape>();
int x_pos = mousework.Width / 2;
int y_pos = mousework.Height - 50;
int bx_pos = mousework.Width / 2;
int by_pos = mousework.Height;
int y_speed = -10;
boolean clicked;
public CreateImage()
{
for (int i = 0; i < 10; i++) {
rect.add(new fallShape(15, 15, rect));
}
Toolkit picx = Toolkit.getDefaultToolkit();
gunMage = picx.getImage("gunner.jpg");
gunMage = gunMage.getScaledInstance(200, -1, Image.SCALE_SMOOTH);
Toolkit pic = Toolkit.getDefaultToolkit();
pixMage = pic.getImage("ballfall3.jpg");
pixMage = pixMage.getScaledInstance(200, -1, Image.SCALE_SMOOTH);
addMouseListener(this);
addMouseMotionListener(new MouseMotionAdapter() {
#Override
public void mouseMoved(MouseEvent e)
{
x_pos = e.getX() - 5;
}
});
}
public void mousePressed(MouseEvent e)
{
if (e.getButton() == 1) {
clicked = true;
}
}
public void mouseReleased(MouseEvent e)
{
if (e.getButton() == 1) {
clicked = false;
}
}
public void mouseExited(MouseEvent e)
{
}
public void mouseEntered(MouseEvent e)
{
}
public void mouseClicked(MouseEvent e)
{
}
public void paint(Graphics g)
{
super.paint(g);
g.drawImage(pixMage, 0, 0, Width, Height, null);
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g.drawImage(gunMage,x_pos,y_pos,10,20,null);
if (clicked) {
by_pos += y_speed;
Shape bullet = new Rectangle2D.Float(bx_pos, by_pos, 3, 10);
g2.setColor(Color.BLACK);
g2.fill(bullet);
g2.draw(bullet);
}
g2.setColor(Color.RED);
for (fallShape b : rect) {
b.move();
g2.fill(b);
}
}
}
public static void main(String[] args)
{
java.awt.EventQueue.invokeLater(new Runnable() {
#Override
public void run()
{
new mousework2().setVisible(true);
}
});
}
}
And:
// My falling shapes class: fallShape
import java.awt.geom.*;
import java.util.*;
public class fallShape extends Rectangle2D.Float
{
public int x_speed, y_speed;
public int l, b;
public int height = mousework.Height;
public int width = mousework.Width;
public ArrayList<fallShape> fall;
public fallShape(int breadth, int length, ArrayList<fallShape> fall)
{
super((int) (Math.random() * (mousework.Width - 20) + 1), 0, breadth, length);
this.b = breadth;
this.l = length;
this.x_speed = (int) Math.random() * (10) + 1;
this.y_speed = (int) Math.random() * (10) + 1;
this.fall = fall;
}
public void move()
{
Rectangle2D rec = new Rectangle2D.Float(super.x, super.y, b, l);
for (fallShape f : fall) {
if (f != this && f.intersects(rec)) {
int rxspeed = x_speed;
int ryspeed = y_speed;
x_speed = f.x_speed;
y_speed = f.y_speed;
f.x_speed = rxspeed;
f.y_speed = ryspeed;
}
}
if (super.x < 0) {
super.x =+ super.x;
//super.y =+ super.y;
x_speed = Math.abs(x_speed);
}
if (super.x> mousework.Width - 30) {
super.x =+ super.x;
super.y =+ super.y;
x_speed =- Math.abs(x_speed);
}
if (super.y < 0) {
super.y = 0;
y_speed = Math.abs(y_speed);
}
super.x += x_speed;
super.y += y_speed;
}
}
if(clicked){
by_pos+=y_speed;
This code only draws the bullet when the mouse is down. This is because you are setting clicked to false in your mouseReleased method:
public void mouseReleased(MouseEvent e){
if(e.getButton()==1)
clicked=false;
}
If you were to remove the body of the mouseReleased method, your bullet would move properly.
However, say you wanted to have more than just one bullet. Currently, your paint method only draws one bullet at a time. To draw multiple bullets, you would need to create a list of the coordinates of the bullets, and add a new coordinate pair to the list whenever you click. Then, in the paint method, just update each position in a for loop.
ArrayList<Integer> by_poss = new ArrayList<>();
by_poss is the list of all the y-positions of your bullets.
public void mousePressed(MouseEvent e){
if(e.getButton() == 1)
by_poss.add(mousework.Height);
}
The mousePressed method adds a new "bullet", in the form of a y-position, to the coordinates.
public void mouseReleased(MouseEvent e){
//do nothing
}
Nothing needs to happen in the mouseReleased method.
//update the bullets
public void paint(Graphics g){
...
g2.setColor(Color.BLACK);
Shape bullet;
for(int i = 0; i < by_poss.size(); i++){
by_poss.set(i, by_poss.get(i) + y_speed); //move the bullet
bullet = new Rectangle2D.Float(bx_pos, by_poss.get(i), 3, 10);
g2.fill(bullet);
g2.draw(bullet);
}
...
}
The for loop in your paint method draws all the bullets, one by one, usin g the y-positions from the by_poss list.

Creating multiple instances of an object. (Game)

I've been asked to make a game for my CS (high school) class as my end of semester assignment. We haven't been taught properly all of the coding required to make a game so my knowledge in this area is very poor. Anyways, the game I am trying to make is something like "Flappy Fall" (an Apple appstore game) where objects fall from the top of the screen and descend to the bottom of the screen. The objective is to catch these objects before they reach the bottom. I am able to get one object to fall and have also created the "catcher", but I am not sure how to create multiple falling objects, nor do I know how to remove the object once it has been caught by the catcher. So far I have classes "JavaGame", "Catcher", and "Ball". Any help would be greatly appreciated.
int x, y;
int t = 1;
private Image dbImage;
private Graphics dbGraphics;
Image player;
Image bkg;
static Catcher p = new Catcher(150, 450);
public JavaGame() {
//Game Images
ImageIcon b = new ImageIcon("bkg.png");
bkg = b.getImage();
//Game properties
setTitle("Game");
setSize(350, 600);
setResizable(false);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
addKeyListener(new Keys());
addMouseMotionListener(new Mouse());
}
public void paint(Graphics g) {
//
dbImage = createImage(getWidth(), getHeight());
dbGraphics = dbImage.getGraphics();
draw(dbGraphics);
g.drawImage(dbImage, 0, 0, this);
}
public void draw(Graphics g) {
g.drawImage(bkg, 0, 0, this); //Creates background
p.draw(g);
//while (t < 100) {
p.b.draw(g);
//t++;
//}
g.setColor(Color.WHITE);
g.drawString(""+p.score, 175, 50);
repaint();
}
public static void main(String[] args) {
JavaGame jg = new JavaGame();
//Threads
Thread p1 = new Thread(p);
p1.start();
Thread ball = new Thread(p.b);
ball.start();
}
public class Keys extends KeyAdapter {
public void keyPressed(KeyEvent e) {
p.keyPressed(e);
}
public void keyReleased(KeyEvent e) {
p.keyReleased(e);
}
}
public class Mouse implements MouseMotionListener {
public void mouseDragged(MouseEvent e) {
p.mouseDragged(e);
}
public void mouseMoved(MouseEvent e) {
p.mouseMoved(e);
}
}
}
int x, y, ranX, xDirection;
int score;
Rectangle catch1;
Ball b = new Ball(170, 1);
public Catcher (int x, int y) {
score = 0;
this.x = x;
this.y = y;
catch1 = new Rectangle(this.x, this.y, 50, 15);
}
public void run() {
try {
while(true) {
move();
Thread.sleep(5);
}
}
catch(Exception e) {
System.out.println("Error");
}
}
public void collision() {
if (b.ball.intersects(catch1)) {
b.ball(Color.blue);
score++;
System.out.println(score);
}
}
public void move() {
collision();
catch1.x += xDirection;
if (catch1.x <= 0)
catch1.x = 0;
if (catch1.x >= 300)
catch1.x = 300;
}
public void setXDirection(int xDir) {
xDirection = xDir;
}
public void keyPressed(KeyEvent m) {
int keyCode = m.getKeyCode();
if (keyCode == m.VK_LEFT) {
setXDirection(-1);
}
if (keyCode == m.VK_RIGHT) {
setXDirection(+1);
}
m.consume();
}
public void keyReleased(KeyEvent m) {
int keyCode = m.getKeyCode();
if (keyCode == m.VK_LEFT) {
setXDirection(0);
}
if (keyCode == m.VK_RIGHT) {
setXDirection(0);
}
m.consume();
}
public void mouseDragged(MouseEvent e) {
catch1.x = e.getX()-25;
e.consume();
}
public void mouseMoved(MouseEvent e) {
catch1.x = e.getX()-25;
e.consume();
}
public void draw(Graphics g) {
g.fillRect(catch1.x, catch1.y, catch1.width, catch1.height);
}
}
int x, y, yDirection;
Rectangle ball;
public Ball (int x, int y) {
this.x = x;
this.y = y;
ball = new Rectangle(this.x, this.y, 10, 10);
}
public void run() {
try{
while(true) {
move();
Thread.sleep(5);
}
}
catch(Exception e) {
System.out.println("Error");
}
}
public void move() {
if (ball.y >= 600) {
ball.y = 600;
}
if (ball.y > 0) {
ball.y++;
}
}
public void setYDirection(int yDir) {
yDirection = yDir;
}
public void draw(Graphics g) {
g.setColor(Color.WHITE);
g.fillRect(ball.x, ball.y, ball.width, ball.height);
System.out.println(ball.x+ " "+ ball.y+ " " + ball.width + " " + ball.height);
}
}
I'd re-organize the code a little. In the main game, you can have a collection of 'Ball' types. I'll leave the collection option up to you. But you'll want to add 'new' Balls to the collection and then remove them once they are caught.
Since I do not want to do your assignment, I am just giving a short answer:
By calling new Ball() multiple times.
Of course you might want to add them to a collection, like
List list = new ArrayList();
list.add(ball);
And remove them from that collection once they are finished.

Categories

Resources