Detecting if a 2D Graphics fill Rect is in another fillRect(eclipse) - java

private JPanel contentPane;
private KeyListener myKeyListener;
JLabel lblUp;
JLabel lblMiddle;
JLabel lblDown;
JButton btnStart;
JLabel lblScore;
int lblu = 0;
int x = 0;
int y = 50;
int u = 1;
int w = 1;
int rxx = 0;
int ryy = 0;
int s = 0;
Timer timer;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Game_1 frame = new Game_1();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Game_1() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel lblScore = new JLabel("0");
lblScore.setHorizontalAlignment(SwingConstants.CENTER);
lblScore.setForeground(Color.GREEN);
lblScore.setBounds(388, 0, 46, 14);
contentPane.add(lblScore);
addKeyListener(this);
}
public void keyPressed(KeyEvent arg0) {
Graphics pen = this.contentPane.getGraphics();
int maxh = contentPane.getHeight();
int maxw = contentPane.getWidth();
if(y < 0){
y = maxh -50;
}
if(y > maxh-45){
y = 0;
}
if (arg0.getKeyCode() == KeyEvent.VK_UP) {
if(u ==0){
pen.setColor(Color.BLACK);
pen.fillRect(0, 0, maxw, maxh);
y = y - 10;
pen.setColor(Color.GREEN);
pen.fillRect(x, y, 50, 50);
pen.setColor(Color.BLACK);
pen.fillRect(x - 50, y, 50, 50);
x = x + 1;
if (x >= maxw) {
pen.fillRect(x - 30, y, 50, 50);
x = 0;
}
}
} else if (arg0.getKeyCode() == KeyEvent.VK_RIGHT) {
if(u ==1){
pen.setColor(Color.BLACK);
pen.fillRect(0, 0, maxw, maxh);
pen.setColor(Color.BLACK);
pen.fillRect(0, 0, maxw, maxh);
Timer timer = new Timer(100, this);
timer.start();
u = 0;
}else if(u ==0){
x = x +10;
}
} else if (arg0.getKeyCode() == KeyEvent.VK_DOWN) {
if(u ==0){
pen.setColor(Color.BLACK);
pen.fillRect(0, 0, maxw, maxh);
pen.setColor(Color.BLACK);
y = y+ 10;
if (x >= maxw) {
pen.fillRect(x - 30, y, 50, 50);
x = 0;
}
}
} else if (arg0.getKeyCode() == KeyEvent.VK_LEFT) {
if(u ==0){
pen.setColor(Color.BLACK);
pen.fillRect(0, 0, maxw, maxh);
pen.setColor(Color.BLACK);
x = x- 10;
if (x < 0) {
pen.fillRect(x - 30, y, 50, 50);
x = maxw;
}
}
}
}
public void keyReleased(KeyEvent arg0) {
}
public void keyTyped(KeyEvent arg0) {
}
public void run() {
}
#Override
public void actionPerformed(ActionEvent arg0) {
Graphics pen = this.contentPane.getGraphics();
int maxh = contentPane.getHeight();
int maxw = contentPane.getWidth();
pen.setColor(Color.BLACK);
pen.fillRect(0, 0, maxw, maxh);
pen.setColor(Color.GREEN);
pen.fillRect(x, y, 50, 50);
pen.setColor(Color.BLACK);
pen.fillRect(x - 50, y, 50, 50);
x = x + 1;
if (x >= maxw) {
pen.fillRect(x - 30, y, 50, 50);
x = 0;
}
if(w ==1){
Random r = new Random();
int ry = r.nextInt(maxh - 0) + 100;
int rx = r.nextInt(maxw - 0) + 100;
rxx = rx;
ryy = ry;
pen.setColor(Color.RED);
pen.fillRect(rx, ry, 10, 10);
w = 0;
}
pen.setColor(Color.RED);
pen.fillRect(rxx, ryy, 10, 10);
if(x-50 <= rxx && x > rxx && y > ryy && y-50 <= ryy){
s ++;
System.out.println("PUNKT");
pen.setColor(Color.BLACK);
pen.fillRect(rxx, ryy, 10, 10);
w = 1;
}
}
}
here is the Problem: it only detects that they touch in the left top >corner(the wrong code is at the end, the last if)
you can start the game by pressing the Right arrow Button on you're Keyboard.Moving upwards: up Key on you're Keyboard.Moving downwards:down Key on your're Keyboard.The right Button also lets you move to the right, the left Button to the left.Picture of the Game

I want, that the Rect detects that it touches the other in every part
of it, not only in the left top corner
Let's assume you've got first rect with: x1, y1, width1, height1 and second rect with x2, y2, width2, height2. The first rect touched the second in every part of it (so the second one is contained in the first one) when x1 <= x2 && x2+width2 <= x1+width2 && y1 <= y2 && y2+height <= y1+height
so
if (x1 <= x2 && x2+width2 <= x1+width2 && y1 <= y2 && y2+height <= y1+height) {
// the second rect is contained in the first rect
}

So I finally fixed it. For those who are interested, here is the fixed part of the code:
if (x+d >= x2 && x <= x2 && y+d >=y2 && y <= y2) {
s++;
d = d + s*10;
System.out.println("PUNKT");
pen.setColor(Color.BLACK);
pen.fillRect(x2, y2, 10, 10);
w = 1;
if (s == 10) {
JOptionPane.showMessageDialog(frame, "Achievement get: " + s + "Punkte!");
}

Related

Java swing game JPanel layout assistance

I'm in the process of making a game which has 3 sections to the JFrame, the game map, a "player view" : just an animation of the player moving and will hopefully include different enemy designs later and finally a inventory section I haven't started on yet.
What would be the best way in terms of class and method layouts to have all these 3 sections of my JPanel able to communicate with one another and dynamically change based on the current situation (having the player view show an enemy when their tile collides with another or have it not update if the player doesnt move (s)).
I don't mind re-writing the entire game just this is my first game and would like some assistance on structure.
And I'm not sure exactly how paintComponent works or repaint() method. Or how draw(Graphics g) is called
to make the graphics???
Code for context and testing:
TextGamePanel.java :
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.Iterator;
import java.util.ArrayList;
import java.util.Random;
public class TextGamePanel extends JPanel implements ActionListener{
private static final int HEIGHT = 30, WIDTH = 30, MAPVISIBILITY = 8;
private static final int SCREEN_WIDTH = 1080;
private static final int SCREEN_HEIGHT = 1080;
private static final int UNIT_SIZE = 36;
private static final int DELAY = 10;
private String[][] mapBlank = new String[HEIGHT][WIDTH];
private ArrayList<Enemies> enemyList = new ArrayList<Enemies>();
private Random random = new Random();
private Players player;
private int turnCounter = 0;
Timer timer;
boolean active = false , movementMade = false;
TextGamePanel(){
this.setPreferredSize(new Dimension(1920, 1080));
this.setFocusable(true);
this.addKeyListener(new MyKeyAdapter());
startGame();
}
public void startGame(){
newPlayer();
active = true;
timer = new Timer(DELAY, this);
timer.start();
}
public void paintComponent(Graphics g){
super.paintComponent(g);
draw(g);
}
public void makeMap(){
for(int row = 0; row < mapBlank.length; row++){
for(int col = 0; col < mapBlank[row].length; col++){
mapBlank[row][col] = "";
}
}
for(Enemies enemy : enemyList){
mapBlank[enemy.getXPos()][enemy.getYPos()] = " *";
}
mapBlank[player.getXPos()][player.getYPos()] = " ^";
}
public void draw(Graphics g){
makeMap();
// These loops generate the
g.setColor(new Color(69, 69, 69));
g.fillRect(1080, 0, 840, 360);
g.setFont(new Font("Times Roman", Font.BOLD, 36));
g.setColor(new Color(74, 74, 74));
for(int x = 0; x < 20; x++){
g.drawString(randomString(50), 1020, UNIT_SIZE + x*UNIT_SIZE/2);
}
for(int i = 0; i < 2; i++){
for(int x = 0; x < 13; x++){
g.setColor(new Color(0+x*10, 0+x*10, 0+x*10));
g.setFont(new Font("Times Roman", Font.BOLD, 10+x*2));
g.drawString(randomString(200), 1020, 268 + x * 8);
}
}
//makes the map background grey
g.setColor(new Color(69, 69, 69));
g.fillRect(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
//Makes light for context of player view range
g.setColor(new Color(227, 201, 109, 50));
g.fillOval((int)(((player.getXPos()) * UNIT_SIZE) - MAPVISIBILITY/2 * UNIT_SIZE), (int)(((player.getYPos()) * UNIT_SIZE) - MAPVISIBILITY/2 *UNIT_SIZE), (int)((MAPVISIBILITY +1) * UNIT_SIZE), (int)((MAPVISIBILITY +1) * UNIT_SIZE));
g.setColor(new Color(227, 180, 109, 50));
g.fillOval((int)(((player.getXPos()) * UNIT_SIZE) - (MAPVISIBILITY/2 - 1) * UNIT_SIZE), (int)(((player.getYPos()) * UNIT_SIZE) - (MAPVISIBILITY/2 - 1) *UNIT_SIZE), (int)((MAPVISIBILITY -1) * UNIT_SIZE), (int)((MAPVISIBILITY -1) * UNIT_SIZE));
g.setColor(new Color(240, 110, 67, 50));
g.fillOval((int)(((player.getXPos()) * UNIT_SIZE) - (MAPVISIBILITY/2 - 2.5) * UNIT_SIZE), (int)(((player.getYPos()) * UNIT_SIZE) - (MAPVISIBILITY/2 - 2.5) *UNIT_SIZE), (int)((MAPVISIBILITY -4) * UNIT_SIZE), (int)((MAPVISIBILITY -4) * UNIT_SIZE));
g.setColor(new Color(255, 255, 255));
g.setFont(new Font("Times Roman", Font.BOLD, 36));
//draws the grid
for(int i = 0; i < SCREEN_HEIGHT/UNIT_SIZE; i++){
g.drawLine(i*UNIT_SIZE, 0, i*UNIT_SIZE, SCREEN_HEIGHT);
}
for(int i = 0; i < SCREEN_WIDTH/UNIT_SIZE; i++){
g.drawLine(0, i*UNIT_SIZE, SCREEN_WIDTH, i*UNIT_SIZE);
}
//draws only yourself and enemy around you given MAPVISIBILITY/2 = view range
int xIndex = -1, yIndex = -1;
for(int row = player.getXPos() - MAPVISIBILITY/2; row < player.getXPos() + 1 + MAPVISIBILITY/2; row++){
xIndex ++;
for(int col = player.getYPos() - MAPVISIBILITY/2; col < player.getYPos() + 1 + MAPVISIBILITY/2; col++){
yIndex++;
try{
g.drawString(mapBlank[row][col], row * UNIT_SIZE, (col + 1) * UNIT_SIZE);
}catch(Exception e){
}
}
}
// inventory section (yet to be made)
g.setColor(Color.blue);
g.fillRect(1080, 360, 840, 720);
}
public void movementPhase(){
turnCounter ++;
updateEnemyMovement();
if(turnCounter == 2){
turnCounter = 0;
newEnemy();
}
}
#Override
public void actionPerformed(ActionEvent e){
if(active){
}
}
public class MyKeyAdapter extends KeyAdapter{
#Override
public void keyPressed(KeyEvent e){
switch(e.getKeyCode()){
case KeyEvent.VK_Q: // Move diagonal left up.
if(player.getXPos() > 0 && player.getYPos() > 0){
player.setXPos(player.getXPos() - 1);
player.setYPos(player.getYPos() - 1);
movementMade = true;
}
break;
case KeyEvent.VK_E: // Move diagonal right up.
if(player.getXPos() < HEIGHT - 1 && player.getYPos() > 0){
player.setXPos(player.getXPos() + 1);
player.setYPos(player.getYPos() - 1);
movementMade = true;
}
break;
case KeyEvent.VK_Z: // Move diagonal left down.
if(player.getXPos() > 0 && player.getYPos() < WIDTH - 1){
player.setXPos(player.getXPos() - 1);
player.setYPos(player.getYPos() + 1);
movementMade = true;
}
break;
case KeyEvent.VK_C: // Move diagonal right down.
if(player.getYPos() < WIDTH - 1 && player.getXPos() < HEIGHT - 1){
player.setXPos(player.getXPos() + 1);
player.setYPos(player.getYPos() + 1);
movementMade = true;
}
break;
case KeyEvent.VK_W: // Move up.
if(player.getYPos() > 0){
player.setYPos(player.getYPos() - 1);
movementMade = true;
}
break;
case KeyEvent.VK_X: // Move down.
if(player.getYPos() < WIDTH - 1){
player.setYPos(player.getYPos() + 1);
movementMade = true;
}
break;
case KeyEvent.VK_A: // Move left.
if(player.getXPos() > 0){
player.setXPos(player.getXPos() - 1);
movementMade = true;
}
break;
case KeyEvent.VK_D: // Move right.
if(player.getXPos() < HEIGHT - 1){
player.setXPos(player.getXPos() + 1);
movementMade = true;
}
break;
case KeyEvent.VK_S: // Dont Move.
movementMade = true;
break;
}
if(movementMade){
movementPhase();
movementMade = false;
}
repaint();
}
}
public void updateEnemyMovement(){
Iterator i = (Iterator) enemyList.iterator();
Enemies enemy = new Enemies();
while(i.hasNext()){
enemy = (Enemies) i.next();
enemy.move(player.getXPos(), player.getYPos());
if(enemy.getXPos() == player.getXPos() && enemy.getYPos() == player.getYPos()){
i.remove();
}
}
}
public void newPlayer(){
player = new Players(random.nextInt((int)SCREEN_WIDTH/UNIT_SIZE), random.nextInt((int)SCREEN_HEIGHT/UNIT_SIZE));
}
public void newEnemy(){
enemyList.add(new Enemies(random.nextInt(HEIGHT), random.nextInt(WIDTH)));
}
public String randomString(int n) {
int leftLimit = 49; //'0'
int rightLimit = 122; //'z'
int targetStringLength = n;
Random random = new Random();
StringBuilder buffer = new StringBuilder(targetStringLength);
for (int i = 0; i < targetStringLength; i++) {
int randomLimitedInt = leftLimit + (int)
(random.nextFloat() * (rightLimit - leftLimit + 1));
buffer.append((char) randomLimitedInt);
}
String generatedString = buffer.toString();
return(generatedString);
}
}
`
Players.java :
public class Players{
private int x, y;
public Players(){
}
public Players(int x, int y){
this.x = x;
this.y = y;
}
/** Positional Methods */
public int getXPos(){
return x;
}
public int getYPos(){
return y;
}
public void setXPos(int x){
this.x = x;
}
public void setYPos(int y){
this.y = y;
}
}
`
Enemies.java :
public class Enemies {
private int x, y;
public Enemies(){
}
public Enemies(int x, int y){
this.x = x;
this.y = y;
}
/** Positional Methods */
public int getXPos(){
return x;
}
public int getYPos(){
return y;
}
public void setXPos(int x){
this.x = x;
}
public void setYPos(int y){
this.y = y;
}
/** Enemy Movement Method */
public void move(int playerX, int playerY){
if(getXPos() == playerX && getYPos() == playerY){ // x = playerX & y = playery
}/** Diagonal right down */
else if(getXPos() < playerX && getYPos() < playerY){ // x < playerX & y < playerY
setXPos(getXPos() + 1); // x + 1
setYPos(getYPos() + 1); // y + 1
}/** Diagonal right up */
else if(getXPos() > playerX && getYPos() < playerY){ // x > playerX & y < playerY
setXPos(getXPos() - 1); // x - 1
setYPos(getYPos() + 1); // y + 1
}/** Diagonal left down */
else if(getXPos() < playerX && getYPos() > playerY){ // x < playerX & y > playerY
setXPos(getXPos() + 1); // x + 1
setYPos(getYPos() - 1); // y - 1
}/** Diagonal right up */
else if(getXPos() > playerX && getYPos() > playerY){ // x > playerX & y > playerY
setXPos(getXPos() - 1); // x - 1
setYPos(getYPos() - 1); // y - 1
}/** Down */
else if(getXPos() < playerX && getYPos() == playerY){ // x < playerX & y = playerY
setXPos(getXPos() + 1); // x + 1
}/** Up */
else if(getXPos() > playerX && getYPos() == playerY){ // x > playerX & y = playerY
setXPos(getXPos() - 1); // x - 1
}/** Right */
else if(getXPos() == playerX && getYPos() < playerY){ // x = playerX & y < playerY
setYPos(getYPos() + 1); // y + 1
}/** Left */
else if(getXPos() == playerX && getYPos() > playerY){ // x = playerX & y > playerY
setYPos(getYPos() - 1); // y - 1
}
}
}
`
TextGameFrame.java :
import javax.swing.*;
public class TextGameFrame extends JFrame{
TextGameFrame(){
this.add(new TextGamePanel());
this.setTitle("Text Game");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setResizable(false);
this.pack();
this.setVisible(true);
this.setLocationRelativeTo(null);
}
}
`
TextGameMain.java :
public class TextGameMain{
public static void main(String[] args){
new TextGameFrame();
}
}
`

Stuck on moving paddle

For my class I need to create a one player pong game. We need to use what we've learned so its simple code and the problem is, while the "while loop" is running, my Keydown thread doesn't seem to work. My teacher isn't helpful at all so that's why i'm here. Please help by only using methods and such that are used in my program.
I've tried moving the ball code into a run thread but i can never seem to actually get that thread running.
public class PongGame extends Applet {
int startup = 0;
int x = 400;
int y = 500;
int x2 = (int) (Math.random() * (600 + 1));
int y2 = (int) (Math.random() * (600 + 1));
int xVelocity = 1;
int yVelocity = 1;
int x2Velocity = 1;
int y2Velocity = 1;
int curry = 700;
int currx = 600;
int counter = 2;
#Override
public void init() {
setSize(1440, 900);
setBackground(Color.black);
setFont(new Font("Helvetica", Font.BOLD, 36));
}
#Override
public boolean keyDown(Event evt, int key) {
startup = startup + 1;
repaint();
if (key == Event.RIGHT) {
currx += 10;
}
if (key == Event.LEFT) {
currx -= 10;
}
if (currx == 1400) {
currx = 10;
}
if (currx == 20) {
currx = 1399;
}
repaint();
return false;
}
public void run(Graphics g) {
startup = 0;
while (counter > 0) {
try {
Thread.sleep(30);
} catch (InterruptedException e) {
}
x += xVelocity;
y += yVelocity;
g.setColor(Color.blue);
g.fillRect(currx, curry, 300, 25);
g.setColor(Color.red);
g.fillOval(x, y, 30, 30);
for (int j = 0; j < 20000000; j++);
g.setColor(Color.black);
g.fillOval(x, y, 30, 30);
//Bounce the ball off the wall or paddle
if (x >= 1400 || x <= 0) {
xVelocity = -xVelocity;
}
if (y >= 800 || y <= 0) {
yVelocity = -yVelocity;
}
if (((y == 675)) && ((currx <= x) && (currx + 300) >= x)) {
yVelocity = -yVelocity;
y = y - 10;
repaint();
}
}
}
public void paint(Graphics g) {
if (startup == 0) {
g.setColor(Color.white);
g.drawString("Welcome To PONG", 0, 100);
g.drawString("Created by Caden Anton", 0, 200);
g.drawString("copyright May 3rd, 2019 ©", 0, 300);
g.drawString("Press any key to continue", 0, 400);
}
if (startup == 1) {
g.setColor(Color.white);
g.drawString("RULES:", 0, 100);
g.drawString("Press the arrwow keys to move the paddle", 0, 200);
g.drawString("Your objective is to keep the ball from touching the ground", 0, 300);
g.drawString("Once the ball hits the ground you lose the game", 0, 400);
}
if (startup >= 2) {
//Input Run thread start here.
}
}
}

How do I remove the red rectangle when it collides with the cyan one?

This is my code:
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
public class Draw extends JComponent implements KeyListener {
Random r = new Random();
int x = 0;
int y = 0;
int a = 5 * r.nextInt(150);
int b = 5 * r.nextInt(90);
Image img1 = Toolkit.getDefaultToolkit().getImage("C:/Users/Administrator/eclipse/My Projects/Game/src/bluebackground1.png");
public Draw(){
addKeyListener(this);
setFocusable(true);
}
//display
public void paint(Graphics g){
g.drawImage(img1, 0, 0, this);
g.setColor(Color.CYAN);
g.fill3DRect(x, y, 50, 50, true);
g.setColor(Color.RED);
g.draw3DRect(a, b, 50, 50, true);
g.setColor(Color.BLACK);
g.drawLine(0, 500, 800, 500);
g.setColor(Color.BLACK);
g.drawString("Press R to restart the game", 10, 540);
g.drawString("Use arrow keys to move", 600, 540);
if(x == a && y == b){
g.setColor(Color.BLACK);
g.setFont(new Font("", Font.PLAIN, 50));
g.drawString("Victory", 300, 550);
}
}
//controls
public void keyPressed(KeyEvent k) {
if(k.getKeyCode() == KeyEvent.VK_UP){
y -= 5;
} else if(k.getKeyCode() == KeyEvent.VK_DOWN){
y += 5;
} else if(k.getKeyCode() == KeyEvent.VK_LEFT){
x -= 5;
} else if(k.getKeyCode() == KeyEvent.VK_RIGHT){
x += 5;
}
if(k.getKeyCode() == KeyEvent.VK_R){
restart();
}
//border
if(x < 0){
x += 5;
} else if(x > 745){
x -= 5;
} else if(y < 0){
y += 5;
} else if (y > 450){
y -= 5;
}
repaint();
}
public void keyReleased(KeyEvent k) {}
public void keyTyped(KeyEvent k) {}
//restart function
public void restart(){
x = 0;
y = 0;
a = 5 * r.nextInt(150);
b = 5 * r.nextInt(90);
}
}
What I want is when the cyan rectangle which is moveable gets inside the red rectangle which is not moveable the red rectangle disappears permanently because the game is not over and the cyan rectangle will have to move more.
How do I remove the red rectangle when it collides with the cyan one?
Store Shape instances in a List. At time of painting, iterate the list and draw each one. When one shape is removed, remove it from the list and call repaint().

Paint components with paintComponent(Graphics g) where g is a local variable

Paint components with paintComponent(Graphics g) where g is a local variable. my problem is whenever i do this it gives my a nullPointerException! i want to be able to output new data later on with another method so i need to stor it as a boject that can be changed later.
Map() {
setPreferredSize(new Dimension(500, 500));
makeMap();
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
for (int x = 25; x <= 500; x += 25) {
for (int y = 25; y <= 500; y += 25) {
g.drawRect(0, 0, x, y);
}
}
for (int i = 2; i <= 399; i++) {
int rand = (int) ((Math.random() * (7)) + 1);
if (rand == 1) {
space = i;
// System.out.println(space);
int x = 0;
int y = 0;
space -= 1;
if ((space / 20.0) >= 1.0) {
x = space % 20;
y = space / 20;
x *= 25;
y *= 25;
g.setColor(Color.BLACK);
g.fillRect(x, y, 25, 25);
} else {
y = space;
y *= 25;
g.setColor(Color.BLACK);
g.fillRect(y, 0, 25, 25);
}
mapInfo.put(i, 1);
}
if ((rand == 2) || (rand == 3)) {
mapInfo.put(i, 2);
} else if (rand == 4) {
mapInfo.put(i, 3);
} else {
mapInfo.put(i, 0);
}
}
mapInfo.put(1, 1234);
mapInfo.put(400, 1234);
}
public void makeMap() {
frame = new JFrame();
panel = new JPanel();
frame.getContentPane().add(panel);
frame.pack();
frame.setVisible(true);
frame.setTitle("MAP");
frame.setBounds(600, 0, 516, 538);
frame.setResizable(false);
panel.setLayout(new BorderLayout());
panel.add(this);
}
public void blockSpace(int space) {
}
public int getEvent(int space) {
return mapInfo.get(space);
}
public static void setPlayerPos() {
g.setColor(Color.BLUE);
g.fillRect(475, 475, 25, 25);
}
}

Collision Detection Java 2D Sprite

So I'm trying to implement collision detection in my game and for some reason the collision isnt working properly.
public class ArenaKeys extends KeyAdapter {
arenaScreenBuild arena;
int xPos = 0, playerFace = 4;
int xPPos = 200, yPPos = 150;
int pX = 40, pY = 30;
AttackAshe aAtk = new AttackAshe();
int[][] mask = new int[400][92];
#SuppressWarnings("static-access")
public void keyPressed(KeyEvent e) {
int keyCode = e.getKeyCode();// Get key pressed
if (keyCode == e.VK_RIGHT) {
playerFace = 4;
xPos += 5;
pX = (xPos + xPPos) / 5;
if (checkBoundary(pX, pY) == (false))
xPos -= 5;
} else if (keyCode == e.VK_LEFT) {
playerFace = 3;
xPos -= 5;
pX = (xPos + xPPos) / 5;
if (checkBoundary(pX, pY) == (false))
xPos += 5;
} else if (keyCode == e.VK_UP) {
playerFace = 2;
yPPos -= 5;
pY = yPPos / 5;
if (checkBoundary(pX, pY) == (false))
yPPos += 5;
} else if (keyCode == e.VK_DOWN) {
playerFace = 1;
yPPos += 5;
pY = yPPos / 5;
if (checkBoundary(pX, pY) == (false))
yPPos -= 5;
}
if (keyCode == e.VK_SPACE) {
aAtk.regArrow(arena.xPosition(), arena.yPosition());
arena.shoot(playerFace);
arena.xArrow = xPPos;
arena.yArrow = yPPos;
} else if (keyCode == e.VK_ESCAPE)
System.exit(0);
arena.moveArena(xPos);
arena.turnPlayer(playerFace);
arena.updateScreen(xPPos, yPPos);
}
public boolean checkBoundary(int x, int y) {
Rectangle t1 = new Rectangle(Turret.x, Turret.y, Turret.WIDTH,
Turret.HEIGHT);
Rectangle p = new Rectangle(pX, pY, Player.WIDTH, Player.HEIGHT);
if (t1.intersects(p))
// if (mask[x][y] == 0)
return false;
else
return true;
}
public static class Turret {
static int x = 168;
static int y = 40;
static final int WIDTH = 50;
static final int HEIGHT = 50;
}
public static class Player {
static final int WIDTH = 25;
static final int HEIGHT = 25;
}
public ArenaKeys(arenaScreenBuild arena) throws Exception {
this.arena = arena;
}
}
Approximately 20 units before the actual turret, the sprite stops being able to move any further. The sprite cannot go above or below the turret even if you go really high or really low.
What seems to be going wrong is that the sprite is colliding into the turret rectangle too early but I don't understand how that it possible. I draw the turret exactly 50 wide, 50 high at 168,40. The player is moving so it's x, y is different everytime but it's dimensions are 25 wide and 25 high.
The original turret is 126x111 approximately but I draw it as 50x50
25x25
public class arenaScreenBuild extends JPanel implements ActionListener {
String picPath = "pictures/";
String[] fileName = { "stageBridge.png", "turret.png", "Ashe.png",
"regArrow.png", "arenaScreen.png" };
ClassLoader cl = arenaScreenBuild.class.getClassLoader();
URL imgURL[] = new URL[5];
Toolkit tk = Toolkit.getDefaultToolkit();
Image imgBG, imgTurret, imgPlayer, imgRegArrow, imgBorder;
Boolean[] ptFunc = new Boolean[3];
int PLAYER_INITIAL_X = 200, PLAYER_INITIAL_Y = 150;
int xPos = 0, xPFace = 150, yPFace = 0;
int xPPos = 200, yPPos = 150;
int xVal, yVal, xArrow, yArrow, xTemp, yTemp;
Timer space;
int counter, facePosition = 1;
public arenaScreenBuild() throws Exception {
for (int x = 0; x < 5; x++) {
imgURL[x] = cl.getResource(picPath + fileName[x]);
}
imgBG = tk.createImage(imgURL[0]);
imgTurret = tk.createImage(imgURL[1]);
imgPlayer = tk.createImage(imgURL[2]);
imgRegArrow = tk.createImage(imgURL[3]);
imgBorder = tk.createImage(imgURL[4]);
for (int x = 0; x < 3; x++)
ptFunc[x] = true;
space = new Timer(100, this);
}
public void updateScreen() {
repaint();
}
public void moveArena(int x) {
xPos = x;
}
public void updateScreen(int x, int y) {
xPPos = x;
yPPos = y;
repaint();
}
public boolean arrow() {
return (true);
}
public void turnPlayer(int face) {
if (face == 4) {
xPFace = 150;
} else if (face == 3) {
xPFace = 100;
} else if (face == 2) {
xPFace = 50;
} else if (face == 1) {
xPFace = 0;
}
if (yPFace == 50)
yPFace = 0;
else if (yPFace == 0)
yPFace = 50;
}
public void paintComponent(Graphics g) {
g.drawImage(imgBG, 10, 30, 610, 490, xPos, 0, xPos + 600, 460, this);
g.drawImage(imgTurret, 850 - xPos, 200, 950 - xPos, 300, 0, 0, 126,
110, this);
g.drawImage(imgTurret, 1350 - xPos, 200, 1450 - xPos, 300, 0, 0, 126,
110, this);
g.drawImage(imgPlayer, xPPos, yPPos, 50 + (xPPos),
50 + (yPPos), xPFace, yPFace, xPFace + 50, yPFace + 50, this);
if (counter <= 5000 && counter > 0)
g.drawImage(imgRegArrow, xArrow, yArrow, this);
g.drawImage(imgBorder, 0, 0, 620, 600, 0, 0, 620, 600, this);
g.setColor(Color.WHITE);
g.drawString("x:" + (xPPos + xPos), 535, 525);
g.drawString("y:" + yPPos, 535, 545);
}
public int xPosition() {
xVal = xPPos + xPos;
return (xVal);
}
public int yPosition() {
yVal = yPPos;
return (yVal);
}
public void shoot(int i) {
facePosition = i;
xTemp = xPosition();
yTemp = yPosition();
space.start();
}
public void actionPerformed(ActionEvent e) {
counter++;
if (facePosition == 4) {
if (counter <= 5000) {
xArrow += 50;
}
}
else if (facePosition == 3) {
if (counter <= 5000) {
xArrow -= 50;
}
}
else if (facePosition == 2) {
if (counter <= 5000) {
yArrow -= 50;
}
}
else if (facePosition == 1) {
if (counter <= 5000) {
yArrow += 50;
}
}
if (xArrow == (xTemp + 100)) {
counter = 0;
space.stop();
}
updateScreen();
}
}
Turns out that my values for the x position were wrong. Also due to my previous boundary code, there were still remenants of it which messed me up therefore not allowing me to see the problem sooner.
For any one looking for how to make the collision detection boundary, just make 2 rectangles and use the
Rectangle rect1 = new Rectangle(topLeftX, topLeftY, rectangleWidth,rectangleHeight);
Rectangle rect2 = new Rectangle(topLeftX, topLeftY, rectangleWidth, rectangleHeight);
if (rect1.intersects(rect2))
//enter code to do if it intersects here

Categories