rotating around a circle without affecting movement - java

I'm trying to create a rectangle that can freely move around the screen whilst also rotating so that it faces a circle or certain point.
My current state makes the object move in a very bizarre fashion and can't seem to fix it.
import javax.swing.JFrame;
public class Start {
public static void main(String[] args) {
JFrame f = new JFrame();
f.setTitle("Minigame");
f.setContentPane(new Panel());
f.setSize(1000, 1000);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
}
}
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JPanel;
import javax.swing.Timer;
public class Panel extends JPanel implements ActionListener, KeyListener{
private Timer timer;
private Graphics2D g2d;
private Planet planet;
private Player player;
private double rotation=0;
private int dx=0;
private int dy=0;
public Panel(){
setFocusable(true);
requestFocus();
planet = new Planet(100,100,100);
player = new Player(200,200,20,50);
}
#Override
public void paintComponent(Graphics g){
super.paintComponent(g);
g2d=(Graphics2D)g;
g2d.fillOval(planet.getX(), planet.getY(), planet.getRadius(), planet.getRadius());
g2d.setColor(Color.BLUE);
g2d.rotate(rotation,planet.centerX(),planet.centerY());
g2d.fillRect(player.getX(), player.getY(), player.getWidth(),player.getHeight());
g2d.dispose();
}
#Override
public void actionPerformed(ActionEvent e) {
rotation=Math.atan2(player.centerX()-planet.centerX(), player.centerY()-planet.centerY());
player.x+=dx;
player.y+=dy;
repaint();
}
#Override
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if (key == KeyEvent.VK_LEFT) {
dx = -5;
}
if (key == KeyEvent.VK_RIGHT) {
dx = 5;
}
if (key == KeyEvent.VK_UP) {
dy = -5;
}
if (key == KeyEvent.VK_DOWN) {
dy = 5;
}
}
#Override
public void keyReleased(KeyEvent e) {
int key = e.getKeyCode();
if (key == KeyEvent.VK_LEFT) {
if (dx==-5)
dx = 0;
}
if (key == KeyEvent.VK_RIGHT) {
if (dx==5)
dx = 0;
}
if (key == KeyEvent.VK_UP) {
if (dy==-5)
dy = 0;
}
if (key == KeyEvent.VK_DOWN) {
if (dy==5)
dy = 0;
}
}
#Override
public void addNotify(){
super.addNotify();
timer=new Timer(10,this);
timer.start();
addKeyListener(this);
}
#Override
public void keyTyped(KeyEvent arg0) {
}
}
public class Planet{
public int x;
public int y;
private int radius;
public Planet(int x,int y,int radius){
this.x=x;
this.y=y;
this.radius=radius;
}
public int getX(){
return x;
}
public int getY(){
return y;
}
public int getRadius(){
return radius;
}
public int centerX(){
return x+(radius/2);
}
public int centerY(){
return y+(radius/2);
}
}
public class Player {
public int x;
public int y;
private int width;
private int height;
public Player(int x,int y,int width,int height){
this.x=x;
this.y=y;
this.width=width;
this.height=height;
}
public int getX(){
return x;
}
public int getY(){
return y;
}
public int getHeight(){
return height;
}
public int getWidth(){
return width;
}
public int centerX(){
return x+(width/2);
}
public int centerY(){
return y+(height/2);
}
}

This is working for me. I changed the sign of the angle, and the way that the player is drawn.
#Override
public void paintComponent(Graphics g){
super.paintComponent(g);
g2d=(Graphics2D)g;
// Draw planet
g2d.fillOval(planet.getX(), planet.getY(), planet.getRadius(), planet.getRadius());
// Draw player
g2d.setColor(Color.BLUE);
g2d.rotate(rotation, player.centerX(), player.centerY());
Rectangle rect = new Rectangle(player.centerX()-(player.getWidth()/2), player.centerY()-(player.getHeight()/2), player.getWidth(),player.getHeight());
g2d.draw(rect);
g2d.dispose();
}
#Override
public void actionPerformed(ActionEvent e) {
rotation=Math.atan2(+player.centerX()-planet.centerX(), - player.centerY()+planet.centerY());
player.x+=dx;
player.y+=dy;
repaint();
}

I haven't checked the calculation of the rotation, but I think fillOval should use twice the radius to draw the planet:
g2d.fillOval(planet.getX(), planet.getY(), planet.getRadius()*2, planet.getRadius()*2);

Related

Drawing Rectangle in AWT is Causing Flickering of the Rectangle to Occur

I am having a hard time trying to figure out why the paddle is flickering when I try to draw it. I know that I could use JFrame, but I am using awt for a specific reason. Any help would be appreciated!
import java.applet.Applet;
import java.awt.Graphics;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.Color;
public class Pong extends Applet implements Runnable,KeyListener{
//applet height and width
final int WIDTH = 700;
final int HEIGHT = 500;
Thread thread;
HumanPaddle p1;
//initialize the applet
public void init(){
this.resize(WIDTH, HEIGHT);
this.addKeyListener(this);
p1 = new HumanPaddle(1);
thread = new Thread(this);
thread.start();
}
//paints the applet
public void paint(Graphics g){
g.setColor(Color.black);
g.fillRect(0,0,WIDTH,HEIGHT);
p1.draw(g);
}
//continually updated within the program
public void update(Graphics g){
paint(g);
}
public void run() {
//infinite loop with a error try and catch
for(;;){
p1.move();
repaint();
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public void keyPressed(KeyEvent e) {
if(e.getKeyCode() == KeyEvent.VK_UP){
p1.setUpAccel(true);
}
else if(e.getKeyCode() == KeyEvent.VK_DOWN){
p1.setDownAccel(true);
}
}
public void keyReleased(KeyEvent e) {
if(e.getKeyCode() == KeyEvent.VK_UP){
p1.setUpAccel(false);
}
else if(e.getKeyCode() == KeyEvent.VK_DOWN){
p1.setDownAccel(false);
}
}
public void keyTyped(KeyEvent arg0) {
}
}
and the HumanPaddle class is:
import java.awt.Color;
import java.awt.Graphics;
public class HumanPaddle implements Paddle{
//declare variables
double y;
double yVel;
boolean upAccel;
boolean downAccel;
int player;
int x;
final double GRAVITY = 0.94;
public HumanPaddle(int player){
upAccel = false;
downAccel = false;
y = 210;
yVel = 0;
if(player == 1)
x = 20;
else
x = 660;
}
public void draw(Graphics g) {
g.setColor(Color.white);
g.fillRect(x, (int)y, 20, 80);
}
public void move() {
if(upAccel){
yVel -= 2;
}
else if(downAccel){
yVel += 2;
}
else if(!upAccel && !downAccel){
yVel *= GRAVITY;
}
y += yVel;
}
//setters
public void setY(double y){
this.y = y;
}
public void setYVel(double yVel){
this.yVel = yVel;
}
public void setUpAccel(boolean upAccel){
this.upAccel = upAccel;
}
public void setDownAccel(boolean downAccel){
this.downAccel = downAccel;
}
public void setPlayer(int player){
this.player = player;
}
public void setX(int x){
this.x = x;
}
//getters
public int getY(){
return (int)y;
}
public double getYVel(){
return yVel;
}
public boolean getUpAccel(){
return upAccel;
}
public boolean getDownAccel(){
return downAccel;
}
public int getPlayer(){
return player;
}
public int getX(){
return x;
}
}
If you are having this problem, the way I solved it was that I added repaint(), which calls the update method in the paint method. It has to be after when you draw in order so that the recursive loop won't leave that part out. I hope I explained that right, kinda a newby programmer!

Detecting Collision between two filled Rectangles

I'm trying to make it print out "Game over" when the Green Square(Cuboid) runs over/into the blue(CuboidKiller) one.
GAME class:
package plugin.dev.wristz;
import java.awt.Graphics;
import java.awt.Image;
import java.util.ArrayList;
import java.util.Random;
import javax.swing.JFrame;
public class Game extends JFrame {
private static final long serialVersionUID = 294623570092988970L;
public static ArrayList<CuboidKiller> killers;
public static int h = 1024, w = 768;
public static Game game;
public static Graphics graphics, g2;
public static Image image;
public static Cuboid cuboid;
public Game(String title) {
setTitle(title);
setSize(1024, 768);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setResizable(true);
setVisible(true);
setLocationRelativeTo(null);
addKeyListener(new KeyHandler(cuboid));
g2 = getGraphics();
paint(g2);
}
public static void main(String[] args) {
cuboid = new Cuboid();
Thread cubi = new Thread(cuboid);
cubi.start();
killers = new ArrayList<CuboidKiller>();
CuboidKiller a = new CuboidKiller(new Random().nextInt(h), new Random().nextInt(w), new Random().nextInt(50) + 20);
killers.add(a);
game = new Game("Killer Cuboids");
}
#Override
public void paint(Graphics g) {
image = createImage(getWidth(), getHeight());
graphics = image.getGraphics();
paintComponent(graphics);
g.drawImage(image, 0, 0, this);
}
public void paintComponent(Graphics g) {
checkGameOver();
cuboid.draw(g);
for (CuboidKiller killer : killers)
killer.draw(g);
repaint();
}
public void checkGameOver() {
for (CuboidKiller killer : killers)
if (killer.isTouching(cuboid))
System.out.println("Game over!");
}
public int getH() {
return h;
}
public void setH(int wh) {
h = wh;
}
public int getW() {
return w;
}
public void setW(int ww) {
w = ww;
}
}
Cuboid class:
package plugin.dev.wristz;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.KeyEvent;
#SuppressWarnings("static-access")
public class Cuboid implements Runnable {
private int x, y, xDirection, zDirection;
public Cuboid() {
this.x = 799;
this.y = 755;
}
public void draw(Graphics g) {
g.setColor(Color.GREEN);
g.fillRect(x, y, 25, 25);
}
public void move() {
x += xDirection;
y += zDirection;
if (x <= 10)
x = 0 + 10;
if (y <= 35)
y = 0 + 35;
if (x >= 1024 - 35)
x = 1024 - 35;
if (y >= 768 - 35)
y = 768 - 35;
}
public void keyPressed(KeyEvent ev) {
int keyCode = ev.getKeyCode();
if (keyCode == ev.VK_LEFT) {
setXDirection(-5);
}
if (keyCode == ev.VK_RIGHT) {
setXDirection(5);
}
if (keyCode == ev.VK_UP) {
setZDirection(-5);
}
if (keyCode == ev.VK_DOWN) {
setZDirection(5);
}
}
public void keyReleased(KeyEvent ev) {
int keyCode = ev.getKeyCode();
if (keyCode == ev.VK_LEFT) {
setXDirection(0);
}
if (keyCode == ev.VK_RIGHT) {
setXDirection(0);
}
if (keyCode == ev.VK_UP) {
setZDirection(0);
}
if (keyCode == ev.VK_DOWN) {
setZDirection(0);
}
}
#Override
public void run() {
try {
while (true) {
move();
Thread.sleep(5);
}
} catch (Exception e) {
System.err.println(e.getMessage());
}
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
public int getXDirection() {
return xDirection;
}
public void setXDirection(int xDirection) {
this.xDirection = xDirection;
}
public int getZ() {
return y;
}
public void setZ(int z) {
this.y = z;
}
public int getZDirection() {
return zDirection;
}
public void setZDirection(int zDirection) {
this.zDirection = zDirection;
}
}
Cuboid Killer:
package plugin.dev.wristz;
import java.awt.Color;
import java.awt.Graphics;
import java.util.HashMap;
public class CuboidKiller {
private int x, y, radius;
private HashMap<Integer, Integer> points;
public CuboidKiller(int x, int y, int radius) {
this.points = new HashMap<Integer, Integer>();
setPoints();
this.x = x;
this.y = y;
this.radius = radius;
}
public void draw(Graphics g) {
g.setColor(Color.blue);
g.fillRect(x, y, radius, radius);
}
public void setPoints() {
this.points.put(x, y);
this.points.put(x + radius, y);
this.points.put(x + radius, y - radius);
this.points.put(x, y - radius);
}
public boolean isTouching(Cuboid cuboid) {
boolean result = true;
//int a = cuboid.getX(), b = cuboid.getZ();
result = true;
return result;
}
public int getRadius() {
return radius;
}
public void setRadius(int radius) {
this.radius = radius;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public HashMap<Integer, Integer> getPoints() {
return points;
}
public void setPoints(HashMap<Integer, Integer> points) {
this.points = points;
}
}
Well, there are two approaches. Either you write it yourself, or you just use what Java 8 provides.
This guy has a very nice explanation on how to detect collision between two rectangles: Java check if two rectangles overlap at any point
But if I were the one writing it, I would just have both classes contain a Rectangle object (http://docs.oracle.com/javase/8/docs/api/java/awt/Rectangle.html), and just call the intersects() function provided by Rectangle. :-)

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!

JFrame add only one class

I'am making a game, and my JFrame add only one class, i don't getting error, but one of two classes dosen't show. I am try to make JFrame frame 2 = new JFrame();, but nothing.
Game.java:
import java.awt.Component;
import javax.swing.JFrame;
public class Game{
private static final int WIDTH = 800;
private static final int HEIGHT = 600;
private static final String TITLE = "Game Dev [ Week #1 ]";
public static void main(String[] args){
JFrame frame = new JFrame();
Player player = new Player();
Rabbit rabbit = new Rabbit();
// Draw on the map
player.setPlayer(250,250);
rabbit.setRabbit(200,200);
// Draw on the map
frame.add(player);
frame.add(rabbit); // Add only this
// Window
frame.setVisible(true);
frame.setSize(WIDTH,HEIGHT);
frame.setTitle(TITLE);
frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
Player.java:
public class Player extends JPanel implements ActionListener, KeyListener{
// Varibles
Timer time = new Timer(5, this);
static int x; double velX = 0;
static int y; double velY = 0;
private BufferedImage player;
boolean W = false;
boolean A = false;
boolean S = false;
boolean D = false;
public void setPlayer(int x, int y){
this.x = x;
this.y = y;
}
public Player(){
time.start();
addKeyListener(this);
setFocusable(true);
setFocusTraversalKeysEnabled(false);
try {
player = ImageIO.read(getClass().getResourceAsStream("/Player.png"));
} catch (IOException e){
e.printStackTrace();
}
}
// Draw player
public void paintComponent(Graphics g){
super.paintComponent(g);
g.drawImage(player, (int)x, (int)y, 100, 100, null);
}
// Set the start up position of player
public void actionPerformed(ActionEvent e){
x += velX;
y += velY;
repaint();
}
// Functions for keyEvent
public void keyPressed(KeyEvent e){
int key = e.getKeyCode();
if(key == KeyEvent.VK_W) // UP
velY = -0.5;
if(key == KeyEvent.VK_A) // LEFT
velX = -0.5;
if(key == KeyEvent.VK_S) // DOWN
velY = 1.5;
if(key == KeyEvent.VK_D) // RIGHT
velX = 1.5;
}
public void keyTyped(KeyEvent e){}
// IF any key released
public void keyReleased(KeyEvent arg0) {
velX = 0;
velY = 0;
W = false;
A = false;
S = false;
D = false;
}
}
Rabbit.java:
public class Rabbit extends JPanel implements ActionListener{
static int x; double velX = 0;
static int y; double velY = 0;
BufferedImage rabbit;
public void setRabbit(int x, int y){
this.x = x;
this.y = y;
}
public Rabbit(){
try {
rabbit = ImageIO.read(getClass().getResourceAsStream("/Rabbit.png"));
} catch (IOException e){
e.printStackTrace();
}
}
public void paintComponent(Graphics g){
super.paintComponent(g);
g.drawImage(rabbit, (int)x, (int)y, 100, 100, null);
}
public void actionPerformed(ActionEvent e){
x += velX;
y += velY;
repaint();
}
}
What's happening is that the JFrame is not combining the graphics for Player and Rabbit; rather, it is placing the player as a panel, and then placing the rabbit. So, the player and the rabbit are always separated. What you want is the Player and Rabbit classes NOT to extend JPanel, but to have a method called paint(Graphics). That way, you can make a class called GamePanel that extends JPanel, and create new methods setPlayer(Player) and setRabbit(Rabbit). The GamePanel class should look like this:
public class GamePanel extends JPanel {
Player player;
Rabbit rabbit;
public void setPlayer(Player player) {
this.player = player;
}
public void setRabbit(Rabbit rabbit) {
this.rabbit = rabbit;
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
player.paint(g);
rabbit.paint(g);
}
}
and your Player class should look like this:
public class Player {
public void paint(Graphics g) {
// How to paint the graphics in the player class
}
}
and your Rabbit class should look the same, except as public class Rabbit.
Hope that helps!
EDIT: Full Script
package game;
import java.awt.Graphics;
public interface Displayable {
public void paint(Graphics graphics);
}
package game;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.ImageObserver;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
public class Rabbit implements Displayable {
private int x, y;
private Image image;
public Rabbit(int x, int y) throws IOException {
this.x = x;
this.y = y;
this.image = ImageIO.read(new File("RABBIT_FILE")); // Replace
// "RABBIT_FILE"
// with the image
// file you have
}
public void paint(Graphics graphics) {
graphics.drawImage(this.image, this.x, this.y, new ImageObserver() {
public boolean imageUpdate(Image img, int infoflags, int x, int y,
int width, int height) {
return false;
}
});
/**
* Optional: JDK 8 only:
*
* graphics.drawImage(this.image, this.x, this.y, (Image img, int
* infoflags, int x0, int y0, int width0, int height0) -> false);
* //Lambda Expression
*/
}
public void setCoordinates(int x, int y) {
this.x = x;
this.y = y;
}
}
package game;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.ImageObserver;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
public class Player implements Displayable {
private int x, y;
private Image image;
public Player(int x, int y) throws IOException {
this.x = x;
this.y = y;
this.image = ImageIO.read(new File("PLAYER_FILE")); // Replace
// "PLAYER_FILE"
// with the image
// file you have
}
public void paint(Graphics graphics) {
graphics.drawImage(this.image, this.x, this.y, new ImageObserver() {
public boolean imageUpdate(Image img, int infoflags, int x, int y,
int width, int height) {
return false;
}
});
/**
* Optional: JDK 8 only:
*
* graphics.drawImage(this.image, this.x, this.y, (Image img, int
* infoflags, int x0, int y0, int width0, int height0) -> false);
* //Lambda Expression
*/
}
public void setCoordinates(int x, int y) {
this.x = x;
this.y = y;
}
}
package game;
import java.awt.Graphics;
import javax.swing.JPanel;
public final class GamePanel extends JPanel {
private static final long serialVersionUID = -385535147711891740L;
private Player player;
private Rabbit rabbit;
public void setPlayer(Player player) {
this.player = player;
}
public void setRabbit(Rabbit rabbit) {
this.rabbit = rabbit;
}
public GamePanel(Player player, Rabbit rabbit) {
this.setPlayer(player);
this.setRabbit(rabbit);
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
this.player.paint(g);
this.rabbit.paint(g);
}
}
package game;
import javax.swing.JFrame;
public final class Main {
public static void main(String... args) {
try {
JFrame frame = new JFrame("Player & Rabbit Game"); // Or whatever
// title
// you have in mind
GamePanel panel = new GamePanel(new Player(0, 0), new Rabbit(0, 0));
frame.add(panel);
frame.setVisible(true);
frame.setDefaultCloseOperation(3);
frame.setExtendedState(6);
} catch (Exception e) {
// Handle Exception if file is corrupted, unable to be read to an
// image, or does not exist
}
}
}

Breakout game, rectagle collision detection

I am trying to make a copy of the breakout game, but I have problems with checking if two objects (the ball and paddle) intersects.
I have this method for collision detection for now:
public static void handleCollisions() {
System.out.println(ball.getBounds()); // just to check that they
System.out.println(paddle.getBounds()); //are there and moving correct
if (ball.getBounds().intersects(paddle.getBounds())) {
System.out.println("collision");
}
}
But even though the rectangles for sure intersect at some points, the method never detects anything. I suppose I have done something wrong with some of the classes.
Here is the main classes:
package assignment1;
import java.awt.*;
import java.awt.event.*;
import java.util.Timer;
import java.util.TimerTask;
import java.util.Vector;
import javax.swing.*;
import javax.swing.plaf.basic.BasicBorders.RadioButtonBorder;
import java.util.Random;
public class Breakout extends TimerTask implements KeyListener {
public static Vector bricks;
public static Ball ball;
public static Paddle paddle;
public static PaintingPanel panel;
public static boolean gameRunning;
public static Breakout game;
public Breakout()
{
}
public static void setupGame()
{
Paddle paddle = new Paddle(350, 790, 100, 10); //initial paddle creation
Ball ball = new Ball(393, 790, 7);
showGUI();
}
public static void beginGame()
{
gameRunning = true;
}
public void run()
{
if(gameRunning == true)
{
Ball.move();
Paddle.move();
handleCollisions();
if(Ball.x < 0 || Ball.x > 800 || Ball.y < 0 || Ball.y > 790){
gameRunning = false;
System.out.println("Game over");
}
}
}
public static void stopGame()
{
}
public static void handleCollisions()
{
System.out.println(ball.getBounds());
System.out.println(paddle.getBounds());
if (ball.getBounds().intersects(paddle.getBounds()))
{
System.out.println("Yay");
}
}
public static void main(String[] args)
{
Timer t = new Timer();
t.schedule(new Breakout(), 0, 40);
panel = new PaintingPanel(PaintingPanel.contents);
setupGame();
beginGame();
while (gameRunning == true)
{
panel.repaint();
}
// TODO a lot
}
private static void showGUI()
{
JFrame frame = new JFrame("Breakout");
game = new Breakout();
frame.addKeyListener(game);
frame.add(panel);
frame.setSize(1000,1000);
frame.setLocationRelativeTo(null); // create game window
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void keyPressed(KeyEvent e) {
Paddle.keyPressed(e);
}
public void keyReleased(KeyEvent e) {
Paddle.keyReleased(e);
}
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub
}
}
package assignment1;
import java.awt.*;
import java.util.Vector;
import javax.swing.*;
public class PaintingPanel extends JPanel{
public static Vector contents;
public PaintingPanel(Vector contents)
{
contents = new Vector();
contents.addElement(Breakout.paddle);
contents.addElement(Breakout.ball);
System.out.println(contents);
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setBackground(Color.GREEN);
g2d.drawRect(2, 2, 800, 800);
Breakout.paddle.paintThis(g2d);
Breakout.ball.paintThis(g2d);
}
}
package assignment1;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Rectangle;
import java.awt.event.KeyEvent;
public class Paddle {
public static int PADDLE_SIZE = 100;
public static int PADDLE_THICKNESS = 10;
public static int centreX = 400; // X Centre of the paddle
public static int centreY = 795; // Y Centre of the paddle
public static int paddleX = centreX - (PADDLE_SIZE/2); // Top left X coordinate
public static int paddleY = centreY -(PADDLE_THICKNESS/2); // Top left Y coordinate
public static int dirX;
public Paddle(int paddleX, int paddleY, int PADDLE_SIZE, int PADDLE_THICKNESS)
{
this.paddleX = paddleX;
this.paddleY = paddleY;
this.PADDLE_SIZE = PADDLE_SIZE;
this.PADDLE_THICKNESS = PADDLE_THICKNESS;
System.out.println("Paddle created at " + paddleX + ", " + paddleY + ", " + PADDLE_SIZE + ", " + PADDLE_THICKNESS);
}
public static void paintThis(Graphics g)
{
g.setColor(Color.BLACK);
g.fillRect(paddleX, paddleY, PADDLE_SIZE, PADDLE_THICKNESS);
g.drawRect(paddleX, paddleY, PADDLE_SIZE, PADDLE_THICKNESS);
}
public static Rectangle getBounds()
{
return new Rectangle(paddleX, paddleX, PADDLE_SIZE, PADDLE_THICKNESS);
}
public static void move()
{
paddleX = paddleX + dirX;
}
public static void keyPressed(KeyEvent e)
{
if (e.getKeyCode() == KeyEvent.VK_LEFT)
{
dirX = -10;
}
if (e.getKeyCode() == KeyEvent.VK_RIGHT)
{
dirX = 10;
}
else {}
}
public static void keyReleased(KeyEvent e)
{
dirX = 0;
}
}
package assignment1;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Rectangle;
import java.util.Random;
public class Ball {
public static int x;
public static int y;
public static int radius;
public final static Color colour = Color.RED;
public static double dirX;
public static double dirY;
public static int speed = 0;
public Ball(int x, int y, int radius)
{
this.x = x;
this.y = y;
this.radius = radius;
dirX = 0;
dirY = -Math.sqrt(1 - dirX*dirX);
System.out.println("Ball created at " + x + ", " + y + ", " + dirX + ", " + dirY);
}
public static void paintThis(Graphics g)
{
g.setColor(colour);
int width = radius*2;
g.fillOval(x, y, width, width);
g.drawOval(x, y, width, width);
}
public static Rectangle getBounds()
{
return new Rectangle(x, y, radius*2, radius*2);
}
public static void move()
{
x = (int) (x-dirX*speed); //check for inaccuracy
y = (int) (y-dirY*speed);
System.out.println("Moved, New X = " + x + ", new Y = "+ y);
}
public void reflect(boolean horizontal, boolean vertical)
{
if (vertical == true)
{
dirX = 0-dirX;
}
if (horizontal == true)
{
dirY = 0-dirY;
}
}
public boolean intersects(Paddle paddle) {
if (getBounds().intersects(Paddle.getBounds())){
return true;
}
else return false;
}
}
https://dl.dropboxusercontent.com/u/65678182/assignment1.rar
The getBounds() method in the Paddle class seems to be the problem. You are returning a Rectangle with upper left coordinates of paddleX and paddleX. I think you meant
return new Rectangle(paddleX, paddleY, PADDLE_SIZE, PADDLE_THICKNESS);
instead.

Categories

Resources