cannot find symbol- class KeyEvent - java

I am trying to make a brickBreaker game with the help of a video but when I compile I get an error in my public voids that involve KeyEvent towards the bottom of the code.
I get the error as follows:
cannot find symbol-class KeyEvent.
package brickBreaker;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent.*;
import java.awt.event.KeyListener;
import java.util.Timer;
import javax.swing.JPanel;
public class Gameplay extends JPanel implements KeyListener, ActionListener{
private boolean play = false;
private int score = 0;
private int totalBricks = 21;
private Timer time;
private int delay = 8;
private int playerX = 310;
private int ballposX = 120;
private int ballposY = 350;
private int balldirX = -1;
private int balldirY = -2;
private MapGenerator map;
public Gameplay(){
map = new MapGenerator(3, 7);
addKeyListener(this);
addActionListener(this);
setFocusable(true);
setFocusTraversalKeysEnabled(false);
// timer = new Timer(delay, this);
// timer.start();
}
public void paint(Graphics g){
//background
g.setColor(Color.black);
g.fillRect(1,1, 692, 592);
//Drawing map
map.draw((Graphics2D)g);
//borders
g.setColor(Color.yellow);
g.fillRect(0,0,3,592);
g.fillRect(0,0,692,3);
g.fillRect(691, 0, 3, 592);
//the paddle
g.setColor(Color.green);
g.fillRect(playerX, 550, 100, 8);
//the ball
g.setColor(Color.yellow);
g.fillOval(ballposX, ballposY, 20, 20);
g.dispose();
}
#Override
public void actionPerformed(ActionEvent e){
timer.start();
if(play){
if(new Rectangle(ballposX, ballposY, 20, 20).intersects(new Rectangle(playerX, 550, 100, 8))){
balldirY = -balldirY;
}
A: for(int i = 0; i < map.map.length; i++){
for(int j = 0; j<map.map[0].length; j++){
if(map.map[i][j] > 0){
int brickX = j* map.brickwidth + 80;
int brickY = i * map.brickheight +50;
int brickwidth = map.brickwidth;
int brickheight = map.brickheight;
Rectangle rect = new Rectangle(brickX, brickY, brickwidth, brickheight);
Rectangle ballRect= new Rectangle(ballposX, ballposY, 20, 20);
Rectangle brickRect = rect;
if(ballRect.intersects(brickRect)){
map.setBrickValue(0, i, j);
totalBricks--;
score += 5;
if(ballposX + 1 <= brickRect.x || ballposX+1 >= brickRect.x+brickRect.width){
balldirX = -balldirX;
} else{
balldirY = -balldirY;
}
break A;
}
}
}
}
ballposX += balldirX;
ballposY+= balldirY;
if(ballposX < 0){
balldirX = -balldirX;
}
if(ballposY < 0){
balldirY = -balldirY;
}
if(ballposX > 670){
balldirX = -balldirX;
}
}
repaint();
}
#Override
public void keyPressed(KeyEvent e){
if(e.getKeyCode() == KeyEvent.VK_RIGHT){
if(playerX >= 600){
playerX = 600;
} else{
moveRight();
}
}
if(e.getKeyCode() == KeyEvent.VK_LEFT){
if(playerX >= 10){
playerX = 10;
} else{
moveLeft();
}
}
}
public void moveRight(){
play = true;
playerX+=20;
}
public void moveLeft(){
play = true;
playerX-=20;
}
}

Change this line import java.awt.event.KeyEvent.*; to this import java.awt.event.KeyEvent;.
EDIT
You need to implement these two methods as well, as they are part of the KeyListener interface.
#Override
public void keyReleased(KeyEvent arg0) {
// TODO
}
#Override
public void keyTyped(KeyEvent arg0) {
// TODO
}

Related

Trying to make a bot to play a simplified Brickbreakers game, but It wont pull variables correctly, (using java.awt.Robot)

I have a Robot method declared in the gameplay class, I have declared the variables but It will not excecated the loop properly, I assume I mis stepped somewhere in the calling of the variables or method. I have it set to pull the X position of the ball and move towards that by using the robot class to press a key, which works just fine on the keyboard (i.e. I can press the keys specified and the paddle moves)
I tried to re declare the variables in the method, the coordinates of both the paddle and ball works, the game functions, but the robot method is not executing at all. I tried to create a new instance of the method in the main method, but nothing changes, I tried to use the "this." function instead of declaring a new object in the method, but it just throws errors. Sorry about the code, I am fairly new to Java, and I am more experienced with C# and unity as opposed to the terminal and stuff like this. Here is the Gameplay Class.
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
import javax.swing.Timer;
import java.awt.Robot;
public class TestGameplay extends JPanel implements KeyListener, ActionListener
{
private boolean play = false;
private int score = 0;
private int totalBricks = 48;
private Timer timer;
private int delay=8;
private int playerX = 310;
public int paddlePos;
private int ballposX = 120;
public int ballX;
private int ballposY = 350;
private int ballXdir = -1;
private int ballYdir = -2;
private MapGenerator map;
public TestGameplay()
{
map = new MapGenerator(4, 12);
addKeyListener(this);
setFocusable(true);
setFocusTraversalKeysEnabled(false);
timer=new Timer(delay,this);
timer.start();
paddlePos = playerX;
ballX = ballposX;
}
public void Robot() throws AWTException {
Robot breaker = new Robot();
int ballPos = ballposX;
if (ballPos > playerX) {
breaker.keyPress(KeyEvent.VK_2);
breaker.delay(100);
breaker.keyRelease(KeyEvent.VK_2);
} else {
breaker.keyPress(KeyEvent.VK_1);
breaker.delay(100);
breaker.keyRelease(KeyEvent.VK_1);
}
}
public void paint(Graphics g)
{
// background
g.setColor(Color.black);
g.fillRect(1, 1, 692, 592);
// drawing map
map.draw((Graphics2D) g);
// borders
g.setColor(Color.yellow);
g.fillRect(0, 0, 3, 592);
g.fillRect(0, 0, 692, 3);
g.fillRect(691, 0, 3, 592);
// the scores
g.setColor(Color.white);
g.setFont(new Font("serif",Font.BOLD, 25));
g.drawString(""+score, 590,30);
// the paddle
g.setColor(Color.green);
g.fillRect(playerX, 550, 100, 8);
// the ball
g.setColor(Color.yellow);
g.fillOval(ballposX, ballposY, 20, 20);
// when you won the game
if(totalBricks <= 0)
{
play = false;
ballXdir = 0;
ballYdir = 0;
g.setColor(Color.RED);
g.setFont(new Font("serif",Font.BOLD, 30));
g.drawString("You Won", 260,300);
g.setColor(Color.RED);
g.setFont(new Font("serif",Font.BOLD, 20));
g.drawString("Press (Enter) to Restart", 230,350);
}
// when you lose the game
if(ballposY > 570)
{
play = false;
ballXdir = 0;
ballYdir = 0;
g.setColor(Color.RED);
g.setFont(new Font("serif",Font.BOLD, 30));
g.drawString("Game Over, Scores: "+score, 190,300);
g.setColor(Color.RED);
g.setFont(new Font("serif",Font.BOLD, 20));
g.drawString("Press (Enter) to Restart", 230,350);
}
g.dispose();
}
public void keyPressed(KeyEvent e)
{
if (e.getKeyCode() == KeyEvent.VK_2)
{
if(playerX >= 600)
{
playerX = 600;
}
else
{
moveRight();
}
}
if (e.getKeyCode() == KeyEvent.VK_1)
{
if(playerX < 10)
{
playerX = 10;
}
else
{
moveLeft();
}
}
if (e.getKeyCode() == KeyEvent.VK_ENTER)
{
if(!play)
{
play = true;
ballposX = 120;
ballposY = 350;
ballXdir = -1;
ballYdir = -2;
playerX = 310;
score = 0;
totalBricks = 21;
map = new MapGenerator(3, 7);
repaint();
}
}
}
public void keyReleased(KeyEvent e) {}
public void keyTyped(KeyEvent e) {}
public void moveRight()
{
play = true;
playerX+=20;
}
public void moveLeft()
{
play = true;
playerX-=20;
}
public void actionPerformed(ActionEvent e)
{
timer.start();
if(play)
{
if(new Rectangle(ballposX, ballposY, 20, 20).intersects(new Rectangle(playerX, 550, 30, 8)))
{
ballYdir = -ballYdir;
ballXdir = -2;
}
else if(new Rectangle(ballposX, ballposY, 20, 20).intersects(new Rectangle(playerX + 70, 550, 30, 8)))
{
ballYdir = -ballYdir;
ballXdir = ballXdir + 1;
}
else if(new Rectangle(ballposX, ballposY, 20, 20).intersects(new Rectangle(playerX + 30, 550, 40, 8)))
{
ballYdir = -ballYdir;
}
// check map collision with the ball
A: for(int i = 0; i<map.map.length; i++)
{
for(int j =0; j<map.map[0].length; j++)
{
if(map.map[i][j] > 0)
{
//scores++;
int brickX = j * map.brickWidth + 80;
int brickY = i * map.brickHeight + 50;
int brickWidth = map.brickWidth;
int brickHeight = map.brickHeight;
Rectangle rect = new Rectangle(brickX, brickY, brickWidth, brickHeight);
Rectangle ballRect = new Rectangle(ballposX, ballposY, 20, 20);
Rectangle brickRect = rect;
if(ballRect.intersects(brickRect))
{
map.setBrickValue(0, i, j);
score+=5;
totalBricks--;
// when ball hit right or left of brick
if(ballposX + 19 <= brickRect.x || ballposX + 1 >= brickRect.x + brickRect.width)
{
ballXdir = -ballXdir;
}
// when ball hits top or bottom of brick
else
{
ballYdir = -ballYdir;
}
break A;
}
}
}
}
ballposX += ballXdir;
ballposY += ballYdir;
if(ballposX < 0)
{
ballXdir = -ballXdir;
}
if(ballposY < 0)
{
ballYdir = -ballYdir;
}
if(ballposX > 670)
{
ballXdir = -ballXdir;
}
repaint();
}
}
}
Here is the Main method
import java.awt.*;
import java.awt.event.KeyEvent;
import java.io.IOException;
import javax.swing.JFrame;
public class Main {
public static void main(String[] args) throws AWTException {
JFrame obj=new JFrame();
TestGameplay gamePlay = new TestGameplay();
Robot robot
obj.setBounds(10, 10, 700, 600);
obj.setTitle("Breakout Ball");
obj.setResizable(false);
obj.setVisible(true);
obj.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
obj.add(gamePlay);
obj.setVisible(true);
}
}
There is the map generator class as well, but It it not relevant to this I think
** I pulled the base game from Git but had to tweak some settings

Brick Bracker Game with Java

I'm new to Java and trying build a brick breaker game with Java. I've searched many instructions from online to build this. I have a problem here that I can't find the solution online anymore.
When I run my code, it works fine, but when the ball hit the top of the frame, it just go through it and never come back. I want let the ball to hit the top and reflect from it. Can anyone help me to solve this problem. I've wrote three classes. Please let me know anything could be helpful!
This is main class:
package brickBreaker;
import javax.swing.JFrame;
class Main {
public static void main(String[] args) {
JFrame obj = new JFrame();
Gameplay gamePlay = new Gameplay();
obj.setBounds(10, 10, 700, 600);
obj.setTitle("Breakout Ball");
obj.setResizable(false);
obj.setVisible(true);
obj.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
obj.add(gamePlay);
}
}
This is Gameplay class:
package brickBreaker;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.Timer;
import javax.swing.JPanel;
public class Gameplay extends JPanel implements KeyListener, ActionListener{
private boolean play = false;
private int score = 0;
private int totalBricks = 21;
private Timer timer;
private int delay = 8;
private int playerX = 310;
private int ballposX = 120;
private int ballposY = 350;
private int ballXdir = -1;
private int ballYdir = -2;
private MapGenerator map;
public Gameplay() {
map = new MapGenerator(3, 7);
addKeyListener(this);
setFocusable(true);
setFocusTraversalKeysEnabled(false);
timer = new Timer(delay, this);
timer.start();
}
public void paint(Graphics g) {
//background
g.setColor(Color.black);
g.fillRect(1, 1, 692, 592);
// drawing map
map.draw((Graphics2D) g);
// scores
g.setColor(Color.white);
g.setFont(new Font("serif", Font.BOLD, 25));
g.drawString(""+score, 590, 30);
// borders
g.setColor(Color.yellow);
g.fillRect(0, 0, 3, 592);
g.fillRect(0 , 0, 692, 3);
g.fillRect(692, 0, 3, 592);
// the paddle
g.setColor(Color.green);
g.fillRect(playerX, 550, 100, 8);
// the ball
g.setColor(Color.yellow);
g.fillOval(ballposX, ballposY, 20, 20);
if (ballposY > 570) {
play = false;
ballXdir = 0;
ballYdir = 0;
g.setColor(Color.red);
g.setFont(new Font("serif", Font.BOLD, 30));
g.drawString("Game Over, Scores: ", 190, 300);
g.setFont(new Font("serif", Font.BOLD, 20));
g.drawString("Press Enter to Restart ", 230, 350);
}
if (totalBricks <= 0) {
play = false;
ballXdir = 0;
ballYdir = 0;
g.setColor(Color.red);
g.setFont(new Font("serif", Font.BOLD, 30));
g.drawString("You Won, Scores: ", 190, 300);
g.setFont(new Font("serif", Font.BOLD, 20));
g.drawString("Press Enter to Restart ", 230, 350);
}
g.dispose();
}
#Override
public void actionPerformed (ActionEvent e) {
timer.start();
if (play) {
if (new Rectangle(ballposX, ballposY, 20, 20).intersects(new Rectangle(playerX, 550, 100, 8))) {
ballYdir = -ballYdir;
}
A: for (int i = 0; i <map.map.length; i++) {
for (int j = 0; j < map.map[0].length; j++) {
if (map.map[i][j] > 0) {
int brickX = j * map.brickWidth + 80;
int brickY = i * map.brickHeight + 50;
int brickWidth = map.brickWidth;
int brickHeight = map.brickHeight;
Rectangle rect = new Rectangle(brickX, brickY, brickWidth, brickHeight);
Rectangle ballRect = new Rectangle(ballposX, ballposY, 20, 20);
Rectangle brickRect = rect;
if (ballRect.intersects(brickRect)) {
map.setBrickValue(0, i, j);
totalBricks--;
score += 10;
if (ballposX + 19 <= brickRect.x || ballposX + 1 >= brickRect.x + brickRect.width) {
ballXdir = -ballXdir;
} else {
ballYdir = -ballYdir;
}
break A;
}
}
}
}
ballposX += ballXdir;
ballposY += ballYdir;
if (ballposX < 0) {
ballXdir = -ballXdir;
}
if (ballposY < 0) {
ballXdir = -ballYdir;
}
if (ballposX > 670) {
ballXdir = -ballXdir;
}
}
repaint();
}
#Override
public void keyReleased (KeyEvent e) {}
#Override
public void keyTyped (KeyEvent e) {}
#Override
public void keyPressed (KeyEvent e) {
if(e.getKeyCode() == KeyEvent.VK_RIGHT) {
if (playerX >= 600) {
playerX = 600;
} else {
moveRight();
}
}
if(e.getKeyCode() == KeyEvent.VK_LEFT) {
if (playerX < 10) {
playerX = 10;
} else {
moveLeft();
}
}
if(e.getKeyCode() == KeyEvent.VK_ENTER) {
if (!play) {
play = true;
ballposX = 120;
ballposY = 350;
ballXdir = -1;
ballYdir = -2;
playerX = 310;
score = 0;
totalBricks = 21;
map = new MapGenerator (3, 7);
repaint();
}
}
}
public void moveRight() {
play = true;
playerX += 20;
}
public void moveLeft() {
play = true;
playerX -= 20;
}
}
This is MapGenerator class:
package brickBreaker;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics2D;
public class MapGenerator {
public int map[][];
public int brickWidth;
public int brickHeight;
public MapGenerator(int row, int col) {
map = new int [row][col];
for (int i = 0; i < map.length; i++) {
for (int j = 0; j < map[0].length; j++) {
map[i][j] = 1;
}
}
brickWidth = 540/col;
brickHeight = 150/row;
}
public void draw(Graphics2D g) {
for (int i = 0; i < map.length; i++) {
for (int j = 0; j < map[0].length; j++) {
if (map[i][j] > 0) {
g.setColor(Color.white);
g.fillRect(j * brickWidth + 80, i * brickHeight + 50, brickWidth,
brickHeight);
g.setStroke(new BasicStroke(3));
g.setColor(Color.black);
g.drawRect(j * brickWidth + 80, i * brickHeight + 50, brickWidth,
brickHeight);
}
}
}
}
public void setBrickValue(int value, int row, int col) {
map[row][col] = value;
}
}
At lines 140-142, you have
if (ballposY < 0) {
ballXdir = -ballYdir;
}
You are reversing the ballXdir rather than the ballYdir when the ball hits the top. Replace with
if (ballposY < 0) {
ballYdir = -ballYdir;
}
and it will bounce off the top correctly.

How to add final score to the end screen?

Hi im new as a coder and i've been working on this very simple box breaker game that i made with tutorial from YT. Now i've started to try modify it and make it more appealing. Tutorial that i used was pretty good but it didn't tell me how to add current score to end where it says "You won, score: ".
Code:
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.Timer;
import javax.swing.JPanel;
public class Gameplay extends JPanel implements KeyListener,
ActionListener {
private boolean play = false;
private int score = 0;
private int totalBricks = 21;
private Timer timer;
private int delay = 8;
private int playerX = 310;
private int ballposX = 200;
private int ballposY = 350;
private int ballXdir = -1;
private int ballYdir = -2;
private MapGenerator map;
public Gameplay() {
map = new MapGenerator(3, 7);
addKeyListener(this);
setFocusable(true);
setFocusTraversalKeysEnabled(false);
timer = new Timer(delay, this);
timer.start();
}
public void paint(Graphics g) {
// background
g.setColor(Color.black);
g.fillRect(1, 1, 692, 592);
//drawing map
map.draw((Graphics2D)g);
//borders
g.setColor(Color.yellow);
g.fillRect(0, 0, 3, 592);
g.fillRect(0, 0, 692, 3);
g.fillRect(691, 0, 3, 592);
//scores
g.setColor(Color.white);
g.setFont(new Font("serif", Font.BOLD, 25));
g.drawString(""+score, 590, 30);
//the paddel
g.setColor(Color.green);
g.fillRect(playerX, 550, 100, 8);
//the ball
g.setColor(Color.yellow);
g.fillOval(ballposX, ballposY, 20, 20);
if(totalBricks <= 0) {
play = false;
ballXdir = 0;
ballYdir = 0;
g.setColor(Color.red);
g.setFont(new Font("serif", Font.BOLD, 30));
g.drawString("You Won, score: ", 260, 300);
g.setFont(new Font("serif", Font.BOLD, 20));
g.drawString("Press ENTER to restart.", 260, 350);
}
if(ballposY > 570) {
play = false;
ballXdir = 0;
ballYdir = 0;
g.setColor(Color.red);
g.setFont(new Font("serif", Font.BOLD, 30));
g.drawString("Game Over, Score: ", 200, 300);
g.setFont(new Font("serif", Font.BOLD, 20));
g.drawString("Press ENTER to restart.", 230, 350);
}
g.dispose();
}
#Override
public void actionPerformed(ActionEvent e) {
timer.start();
if(play) {
if(new Rectangle(ballposX, ballposY, 20, 20).intersects(new
Rectangle(playerX, 550, 100, 8))) {
ballYdir = -ballYdir;
}
A: for(int i = 0; i<map.map.length; i++) {
for(int j = 0; j<map.map[0].length; j++) {
if(map.map[i][j] > 0) {
int brickX = j* map.brickWidth + 80;
int brickY = i* map.brickHeight + 50;
int brickWidth = map.brickWidth;
int brickHeight = map.brickHeight;
Rectangle rect = new Rectangle(brickX, brickY,
brickWidth, brickHeight);
Rectangle ballRect = new Rectangle(ballposX,
ballposY, 19,19);
Rectangle brickRect = rect;
if(ballRect.intersects(brickRect)) {
map.setBrickValue(0, i, j);
totalBricks--;
score += 5;
if(ballposX + 19 <= brickRect.x && ballposX + 1 >=
brickRect.x + brickRect.width) {
ballXdir = -ballXdir;
} else {
ballYdir = -ballYdir;
}
break A;
}
}
}
}
ballposX += ballXdir;
ballposY += ballYdir;
if(ballposX < 0) {
ballXdir = -ballXdir;
}
if(ballposY < 0) {
ballYdir = -ballYdir;
}
if(ballposX > 670) {
ballXdir = -ballXdir;
}
}
repaint();
}
#Override
public void keyReleased(KeyEvent e) {}
#Override
public void keyTyped(KeyEvent e) {}
#Override
public void keyPressed(KeyEvent e) {
if(e.getKeyCode() == KeyEvent.VK_RIGHT) {
if(playerX >=600) {
playerX = 600;
} else {
moveRight();
}
}
if(e.getKeyCode() == KeyEvent.VK_LEFT) {
if(playerX < 10) {
playerX = 10;
} else {
moveLeft();
}
}
if(e.getKeyCode() == KeyEvent.VK_ENTER) {
if(!play) {
play = true;
ballposX = 200;
ballposY = 350;
ballXdir = -1;
ballYdir = -2;
playerX = 310;
score = 0;
totalBricks = 21;
map = new MapGenerator(3, 7);
repaint();
}
}
}
public void moveRight() {
play = true;
playerX+=20;
}
public void moveLeft() {
play = true;
playerX-=20;
}
}
"You Won, score: " + score
in java you can combine strings to make longer strings in this case "You Won, Score: " is a string and when you add the score to it score is converted to a string and is combined with the first part to give you what you want.
https://docs.oracle.com/javase/tutorial/java/data/strings.html

Java game Mouse input on buttons not working

I'm trying to make mouse input work in my Java game, but i can't seem to figure it out. I want to click where i made my button and it should change my State from End to Game and respawn my player and my bullet enemies. Why does the following code not change my State to Game instead of End?
My End Class
package BullHellSpel;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.Random;
import BullHellSpel.Game.STATE;
public class End extends MouseAdapter{
private Game game;
private Handler handler;
private HUD hud;
private Random r = new Random();
public End(Game game, Handler handler, HUD hud){
this.game = game;
this.handler = handler;
this.hud = hud;
}
public void mouseClicked(MouseEvent e){
int mx = e.getX();
int my = e.getY();
if(game.gameState == STATE.End){
if(mouseOver(mx, my, 75, 100, 200, 70)){
game.gameState = STATE.Game;
handler.addObject(new Player(Game.WIDTH, Game.HEIGHT, ID.player, handler));
for(int i = 0; i < 5; i++)
handler.addObject(new Bullet(r.nextInt(Game.WIDTH), -1, ID.bullet, handler));
}
}
}
public void mouseReleased(MouseEvent e){
}
private boolean mouseOver(int mx, int my, int x, int y, int width, int height){
if(mx < x && mx > x + width){
if(my < y && my > y + height){
return true;
}else return false;
}else return false;
}
public void tick() {
}
public void render(Graphics g) {
Font fnt = new Font("arial", 1, 20);
Font fnt1 = new Font("arial", 1, 16);
g.setColor(Color.white);
g.setFont(fnt);
g.drawString("You lost with a score of: " + hud.getScore(), 40, 50);
g.setFont(fnt1);
g.drawRect(75, 100, 200, 70);
g.drawString("Retry Game", 90, 140);
g.drawRect(75, 215, 200, 70);
g.drawString("Quit Game", 90, 255);
}
}
In my game Class:
package BullHellSpel;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Graphics;
import sun.applet.Main;
import java.awt.image.BufferStrategy;
import java.io.IOException;
import java.util.Random;
public class Game extends Canvas implements Runnable {
/**
*
*/
private static final long serialVersionUID = 1L;
public static final int WIDTH = 360, HEIGHT = 640 / 1;
private boolean running = false;
private Thread thread;
private Random r;
private Handler handler;
private HUD hud;
private Spawn spawner;
private End end;
private Menu menu;
public enum STATE {
End,
Menu,
Game;
};
public STATE gameState = STATE.Game;
public Game(){
handler = new Handler();
hud = new HUD();
end = new End(this, handler, hud);
menu = new Menu(this, handler, hud);
this.addKeyListener(new KeyInput(handler));
this.addMouseListener(end);
this.addMouseListener(menu);
new Window(WIDTH, HEIGHT, "Space dodgers", this);
spawner = new Spawn(handler, hud);
r = new Random();
if(gameState == STATE.Game){
handler.addObject(new Player(r.nextInt(WIDTH), r.nextInt(HEIGHT), ID.player, handler));
for(int i = 0; i < 5; i++)
handler.addObject(new Bullet(r.nextInt(Game.WIDTH), -1, ID.bullet, handler));
}
}
public synchronized void start(){
thread = new Thread(this);
thread.start();
running = true;
}
public synchronized void stop(){
try{
thread.join();
running = false;
}catch(Exception e){
e.printStackTrace();
}
}
public void run()
{
long lastTime = System.nanoTime();
double amountOfTicks = 60.0;
double ns = 1000000000 / amountOfTicks;
double delta = 0;
long timer = System.currentTimeMillis();
int frames = 0;
while(running)
{
long now = System.nanoTime();
delta += (now - lastTime) / ns;
lastTime = now;
while(delta >=1)
{
tick();
delta--;
}
if(running)
render();
frames++;
if(System.currentTimeMillis() - timer > 1000)
{
timer += 1000;
System.out.println("FPS: "+ frames);
frames = 0;
}
}
stop();
}
private void tick(){
handler.tick();
if(gameState == STATE.Game)
{
hud.tick();
spawner.tick();
if(HUD.HEALTH <= 0){
HUD.HEALTH = 100;
handler.object.clear();
gameState = STATE.End;
}
}else if(gameState == STATE.End){
end.tick();
}else if(gameState == STATE.Menu){
menu.tick();
}
}
private void render(){
BufferStrategy bs = this.getBufferStrategy();
if(bs == null){
this.createBufferStrategy(3);
return;
}
Graphics g = bs.getDrawGraphics();
//HIER KAN JE SHIT TEKENEN
g.setColor(Color.BLACK);
g.fillRect(0, 0, WIDTH, HEIGHT);
//g.drawImage(bg, 0, 0, this);
handler.render(g);
if(gameState == STATE.Game)
{
hud.render(g);
}else if(gameState == STATE.End){
end.render(g);
}else if(gameState == STATE.Menu){
menu.render(g);
}
g.dispose();
bs.show();
}
public static int clamp(int var, int min, int max){
if(var >= max)
return var = max;
else if(var <= min)
return var = min;
else
return var;
}
public static void main(String args[]){
new Game();
}
}

Movement while rotating Java

Im trying to create a top down space ship rpg and I cant seem to get it to move correctly. It wont turn at the correct angles for example if I have it at say a 70 degree angle it will move at a 45 degree angle. Can anyone help? Im building it in netbeans if you want to test it to see what I mean.
package games;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.geom.AffineTransform;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Rotation extends JPanel implements KeyListener{
private static double i = 0, inc = 0.1, iBase, speed = 0, maxTurnSpeed = 2;
private static int xPos = 100, yPos = 100, width = 100, height = 50;
static boolean pressedA = false, pressedD = false, slowdown = false;
public static void main(String[] args) throws InterruptedException {
System.out.println(i);
JFrame f = new JFrame();
Rotation r = new Rotation();
f.add(new Rotation());
f.setSize(600, 600);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.addKeyListener(r);
while(true){
move();
accelerate();
f.repaint();
Thread.sleep(10);
}
}
public static void move(){
xPos += speed * Math.cos(Math.toRadians(i));
yPos += speed * Math.sin(Math.toRadians(i));
System.out.println(i);
}
public static void accelerate(){
//=========Rotational speed acceleration========
if(i>= 360)
i=0;
if(i<= -360)
i=0;
if(pressedA)
i-=inc;
if(pressedD)
i+=inc;
if(inc<maxTurnSpeed && !slowdown && (pressedA || pressedD))
inc+= 0.01;
if(slowdown && inc>=0.02) {
inc-=0.2;
if(inc <= 0.02){
slowdown = false;
pressedA = false;
pressedD = false;
inc = 0;
}
if(pressedA)
i-=inc;
if(pressedD)
i+=inc;
}
//=========Frontal speed Acceleration=========
//i = Math.round10(i, -2);
//System.out.println(inc);
}
public void paint(Graphics g) {
Graphics2D g2d = (Graphics2D) g.create();
g2d.setPaint(new Color(150, 150, 150));
g2d.fillRect(20, 20, 80, 50);
g2d.translate(180, -50);
g2d.rotate(Math.toRadians(i), xPos+width/2, yPos+height/2);
g2d.fillRect(xPos, yPos, width, height);
g2d.dispose();
//System.out.println("repainted");
}
public void keyPressed(KeyEvent e) {
int keyCode = e.getKeyCode();
if (keyCode == KeyEvent.VK_W) {
System.out.println("W is pressed");
speed = 2;
slowdown = false;
maxTurnSpeed = 1;
}
if (keyCode == KeyEvent.VK_S) {
System.out.println("S is pressed");
speed = -1;
slowdown = false;
maxTurnSpeed = 1;
}
if (keyCode == KeyEvent.VK_A) {
System.out.println("A is pressed");
slowdown = false;
pressedA = true;
}
if (keyCode == KeyEvent.VK_D) {
System.out.println("D is pressed");
slowdown = false;
pressedD = true;
}
this.i=i;
}
#Override
public void keyTyped(KeyEvent e) {
}
#Override
public void keyReleased(KeyEvent e) {
speed = 0;
slowdown = true;
maxTurnSpeed = 2;
}
}

Categories

Resources