Java-Gaming.org    
Featured games (81)
games approved by the League of Dukes
Games in Showcase (499)
Games in Android Showcase (118)
games submitted by our members
Games in WIP (567)
games currently in development
News: Read the Java Gaming Resources, or peek at the official Java tutorials
 
    Home     Help   Search   Login   Register   
Pages: [1]
  ignore  |  Print  
  Collision Detection Problems  (Read 1433 times)
0 Members and 1 Guest are viewing this topic.
Offline tyeeeee1
« Posted 2013-03-15 00:50:18 »

Hey, for the past two hours or so I've been attempting to add collision detection into my program but for some reason I just can't seem to figure out how to do it. I know that I'm supposed to use .intersects() and I've managed to get this working, somewhat, before in a different program but this one is a bit different so it's just thrown me off a bit.

The player's character is always centered on the screen, I've made sure of that. The screen moves around the player instead of the player moving around the screen. The map is loaded and then re-rendered depending on where the player moves. I can't figure out how to do .intersects() with the way that I've made the movement.

If anyone can figure out a way to get it working or has an idea of what I can try to get this working it'll help a lot.

Code Related to Map/Character Movement:

KeyboardListener
1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
24  
25  
26  
27  
28  
29  
30  
31  
32  
33  
34  
35  
36  
37  
38  
39  
40  
41  
42  
43  
44  
45  
46  
47  
48  
49  
50  
51  
52  
53  
54  
55  
56  
57  
58  
59  
60  
61  
62  
63  
64  
65  
66  
67  
68  
69  
70  
71  
72  
73  
74  
75  
76  
77  
78  
79  
80  
81  
82  
83  
84  
85  
86  
87  
88  
89  
90  
91  
92  
93  
94  
95  
96  
97  
98  
99  
100  
101  
102  
103  
104  
105  
106  
107  
108  
109  
110  
111  
112  
113  
114  
115  
116  
117  
118  
119  
120  
121  
122  
123  
124  
125  
126  
127  
128  
129  
130  
131  
132  
133  
134  
135  
136  
137  
138  
139  
140  
141  
142  
143  
144  
145  
146  
147  
148  
149  
150  
151  
152  
153  
154  
155  
156  
157  
158  
159  
160  
161  
162  
163  
164  
165  
166  
167  
168  
169  
170  
package Functions;

import java.awt.Component;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

public class KeyboardListener implements KeyListener
{
    int xpos = 0; //Player's X and Y positions on the current map.
   int ypos = 0;
    int direction = 0; //0 left, 1 up, 2 right, 3 down
   boolean walking = false, inventory = false, escapeKeyPressed = false, screenshotKeyPressed = false;
   
    public KeyboardListener(Component x)
    {
        x.addKeyListener(this);
    }

    public void keyPressed(KeyEvent event)
    {
        int keyCode = event.getKeyCode();
        System.out.println("Walking:"+walking+"  KeyCode:"+keyCode+"  Direction:"+direction);
        switch(keyCode)
        {
            //Movement Controls
           case 87: //w key pressed
               direction = 1;
                walking = true;
                ypos--;
                break;
            case 65: //a key pressed
               direction = 0;
                walking = true;
                xpos--;
                break;
             case 83: //s key pressed
               direction = 3;
                walking = true;
                ypos++;
                break;
            case 68: //d key pressed
               direction = 2;
                walking = true;
                xpos++;
                break;
            case 38: //up arrow key pressed
               direction = 1;
                walking = true;
                ypos--;
                break;
            case 37: //left arrow key pressed
               direction = 0;
                walking = true;
                xpos--;
                break;
            case 40: //down arrow key pressed
               direction = 3;
                walking = true;
                ypos++;
                break;
            case 39: //right arrow key pressed
               direction = 2;
                walking = true;
                xpos++;
                break;
            case 73: //i key pressed
               inventory = true;
                break;
            case 27: //escape key pressed
               escapeKeyPressed = true;
                break;
            case 113: //F2 key pressed
               screenshotKeyPressed = true;
                break;
        }
    }

     public void keyReleased(KeyEvent event)
     {
        int keyCode = event.getKeyCode();
       
        switch(keyCode)
        {
            //Movement Controls
           case 87: //w key released
               walking = false;
                break;
            case 65: //a key released
               walking = false;
                break;
            case 83: //s key released
               walking = false;
                break;
            case 68: //d key released
               walking = false;
                break;
            case 38: //up arrow key released
               walking = false;
                break;
            case 37: //left arrow key released
               walking = false;
                break;
            case 40: //down arrow key released
               walking = false;
                break;
            case 39: //right arrow key released
               walking = false;
                break;
            case 73: //i key released
               break;
            case 27: //escape key released
               escapeKeyPressed = false;
                break;
            case 113: //F2 key released
               break;
               
        }
    }

    public void keyTyped(KeyEvent event) //This needs to be here or else an abstract error will be shown when compiling, don't worry; Just keep this here.
   {
    }
   
    //Get Methods
   public int getXpos()
    {
        return xpos;
    }
   
    public int getYpos()
    {
        return ypos;
    }
   
    public int getDirection()
    {
        return direction;
    }
   
    public boolean getWalking()
    {
        return walking;
    }
   
    public boolean getInventory()
    {
        return inventory;
    }
   
    public boolean getEscapeKeyPressed()
    {
        return escapeKeyPressed;
    }
   
    public boolean getScreenshotKeyPressed()
    {
        return screenshotKeyPressed;
    }
   
    //Set Methods
   public void setInventory()
    {
        inventory = false;
    }
   
    public void setScreenshotKeyPressed(boolean x)
    {
        screenshotKeyPressed = false;
    }
}


Rendering Player/Map
1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
24  
25  
26  
27  
28  
29  
30  
31  
32  
33  
34  
35  
36  
37  
38  
39  
40  
41  
42  
43  
44  
45  
46  
47  
48  
49  
50  
51  
52  
53  
54  
55  
56  
57  
58  
59  
60  
61  
62  
63  
64  
65  
66  
67  
68  
69  
70  
71  
72  
73  
74  
75  
76  
77  
78  
79  
80  
81  
82  
83  
84  
85  
86  
87  
88  
89  
90  
91  
92  
93  
94  
95  
96  
97  
98  
99  
100  
101  
102  
103  
104  
105  
106  
107  
108  
109  
package Interface;

import Functions.KeyboardListener;
import Functions.ResourceLoader;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.RenderingHints;

public class ScreenGame extends Screen
{
    private KeyboardListener keyboard;
    private int spriteCounter = 0;
    private boolean gamePaused = false, inventoryScreenPaused = true;
    private ResourceLoader resourceLoader;
    private GameCanvas canvas;
    private static int counter = 0;
   
    public ScreenGame(GameCanvas canvas, KeyboardListener keyboardListener)
    {
        this.resourceLoader = new ResourceLoader();
        keyboard = keyboardListener;
        this.canvas = canvas;
    }
   
    public void tick()
    {
    }
   
    public void render(Graphics2D graphics)
    {
        counter++;
       
        //Check which screen to render.
       if(keyboard.getInventory() == true)
        {
            gamePaused = true;
            inventoryScreenPaused = false;
        }

        RenderingHints renderingHints = new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        renderingHints.put(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
        graphics.setRenderingHints(renderingHints);
       
        int width = 10;
        int height = 10;

        //Render Map

        for(int row = 0; row < height; row++)
        {
            for(int column = 0; column < width; column++)
            {
                if(resourceLoader.getMap()[column][row] == -1237980) //To change the movement speed just times all of the .getXpos and .getYpos parts by a speed multiplier
               {
                    graphics.setColor(Color.RED);
                    graphics.fillRect(column*40 - keyboard.getXpos(), row*40 - keyboard.getYpos(), 40, 40);
                }
                else if(resourceLoader.getMap()[column][row] == -3584)
                {
                    graphics.setColor(Color.YELLOW);
                    graphics.fillRect(column*40 - keyboard.getXpos(), row*40 - keyboard.getYpos(), 40, 40);
                }
                else if(resourceLoader.getMap()[column][row] == -16735512)
                {
                    graphics.setColor(Color.BLUE);
                    graphics.fillRect(column*40 - keyboard.getXpos(), row*40 - keyboard.getYpos(), 40, 40);
                }
            }
         }
       
        //Render Player
       if (keyboard.getWalking() == false)
        {
            spriteCounter = 0;
            counter = 0;
        }
        else if(keyboard.getWalking() == true && spriteCounter == 0)
        {
            spriteCounter = 1;
        }
       
        int direction = keyboard.getDirection();
       
        if (spriteCounter == 0 && keyboard.getWalking() == false)
        {
            graphics.drawImage(resourceLoader.getSprite(0, direction, spriteCounter), 628, 499, null);
        }
        else if (spriteCounter == 1 && keyboard.getWalking() == true && counter >= 15)
        {
             graphics.drawImage(resourceLoader.getSprite(0, direction, spriteCounter), 628, 499, null);
             spriteCounter++;
             counter = 0;
        }
        else if (spriteCounter == 1 && keyboard.getWalking() == true && counter < 15)
        {
             graphics.drawImage(resourceLoader.getSprite(0, direction, spriteCounter), 628, 499, null);
        }
        else if (spriteCounter == 2 && keyboard.getWalking() == true && counter >= 15)
        {
            graphics.drawImage(resourceLoader.getSprite(0, direction, spriteCounter), 628, 499, null);
            spriteCounter--;
            counter = 0;
        }
        else if (spriteCounter == 2 && keyboard.getWalking() == true && counter < 15)
        {
            graphics.drawImage(resourceLoader.getSprite(0, direction, spriteCounter), 628, 499, null);
        }
    }
}


The map is loaded depending on the RGB values of each pixel on a small .png image.

Offline HeroesGraveDev

JGO Kernel


Medals: 260
Projects: 11
Exp: 2 years


┬─┬ノ(ಠ_ಠノ)(╯°□°)╯︵ ┻━┻


« Reply #1 - Posted 2013-03-15 06:31:38 »

You need to learn how to separate logic and rendering.

Also:

Graphics2D.translate()

Use it.

Offline 65K
« Reply #2 - Posted 2013-03-15 06:35:02 »

Before you try to fiddle with collision detection, I highly recommend to take a step back and divide rendering from the rest, meaning character movement, collision detection and all other game logic.
Then do not use magic constants, what is -16735512 ? Makes it unreadable, especially for outsiders.

Each character has its map location, collision detection will be based on that, as will be any movement stuff. After updating the internal game state/logic, everything gets into the rendering method.

Games published by our own members! Check 'em out!
Legends of Yore - The Casual Retro Roguelike
Offline Jimmt
« League of Dukes »

JGO Kernel


Medals: 133
Projects: 4
Exp: 3 years



« Reply #3 - Posted 2013-03-15 16:34:50 »

Yes, for readibility you should use the key statics (KeyEvent.VK_whateverkey).
Also, what does a KeyBoardListener have to do with your player's inventory? Listeners should be for getting events only.
Offline tyeeeee1
« Reply #4 - Posted 2013-03-15 17:05:52 »

Guess I'll need to a bit of re-writing before I figure out collision detection then.
I've fixed up the KeyListener with the keyCode.VK_key's, as for this method:
1  
2  
3  
4  
public boolean getInventory()
{
      return inventory;
}


It just gets a boolean saying whether the I key, used to open up the inventory, has been pressed. ATM this does nothing as I haven't done anything with the inventory yet.

As for the magic constants, whatever that means, they're used to figure out the RGB value of each pixel; I'm not sure of any other way to do it atm. I do agree that it's unreadable though.

Now about separating the state/logic and the rendering. I thought I wasn't supposed to do that since all I'd be doing is creating another class that stores a bunch of static variables as far as I can see. All my code is doing is getting resources and re-drawing them depending on where the player is. It doesn't seem as if there is much of anything to separate.
Offline Axeman

Senior Member


Medals: 7



« Reply #5 - Posted 2013-03-15 21:04:01 »

you can for example do

final int MAGICALNUMBER = -16735512; Smiley

As for separating logic from rendering: perhaps that´s why you´re having problems with the collision detection? You want to update positions on everything that´s moving, check for collision and then, when everything is sorted out, render.

ps. Why would you make a new class with static variables..?
Offline tyeeeee1
« Reply #6 - Posted 2013-03-15 22:29:10 »

you can for example do

final int MAGICALNUMBER = -16735512; Smiley

As for separating logic from rendering: perhaps that´s why you´re having problems with the collision detection? You want to update positions on everything that´s moving, check for collision and then, when everything is sorted out, render.

ps. Why would you make a new class with static variables..?


Ah, that makes sense. Well, the only thing I see that I could separate are a few variables that keep track of misc data so I'd just do something that I was told not to do and throw them all into a random variable class as static variables and just use them wherever and whenever I want without having to care about get/set methods and stuff like that. But, because I was not told to do that, I'm not going to do that.

I'll keep looking at the code and see if I can figure out what to separate I guess.
Offline 65K
« Reply #7 - Posted 2013-03-16 06:07:04 »

You have get used to start with a different mindset. All of those modifications and updates of the virtual game world are possible without actually showing them and tying them to specific graphics classes. The game logic should be runnable on a server without graphics sub system.
And if you really want to learn how to set up and connect classes and objects, stay away from statics for quiet a while.

Offline tyeeeee1
« Reply #8 - Posted 2013-03-16 14:20:04 »

So, what I think you're saying, is that I need to have, for example, a class that just deals with changing the numbers of where the player, sprites and map are and then do something like .getPlayerX(), .getPlayerY(), getSpriteX(), .getSpriteY(), etc... instead of changing the numbers in the same class that I'm doing graphics in?
Offline 65K
« Reply #9 - Posted 2013-03-16 14:27:56 »

So, what I think you're saying, is that I need to have, for example, a class that just deals with changing the numbers of where the player, sprites and map are and then do something like .getPlayerX(), .getPlayerY(), getSpriteX(), .getSpriteY(), etc... instead of changing the numbers in the same class that I'm doing graphics in?
Yes, for example:
- world class where sprites live in
- sprites with position, velocity, etc.
- movement handler responding to user input and updating sprite properties
- collisision detector called from the movement handler or being actually the same class
- renderer taking the world and showing a snapshot during each game loop pass

Games published by our own members! Check 'em out!
Legends of Yore - The Casual Retro Roguelike
Offline Jimmt
« League of Dukes »

JGO Kernel


Medals: 133
Projects: 4
Exp: 3 years



« Reply #10 - Posted 2013-03-16 16:09:42 »

1  
2  
3  
4  
public boolean getInventory()
{
      return inventory;
}


It just gets a boolean saying whether the I key, used to open up the inventory, has been pressed. ATM this does nothing as I haven't done anything with the inventory yet.
Should be the player's inventory, not the keyBoardListener. Listeners should be more of an inbetween than actual base classes. I would just have it with a getInventory() method in your player class and with your keyBoardListener calling that method upon the desired keypress.
Pages: [1]
  ignore  |  Print  
 
 
You cannot reply to this message, because it is very, very old.

 

Add your game by posting it in the WIP section,
or publish it in Showcase.

The first screenshot will be displayed as a thumbnail.

Pippogeek (39 views)
2014-09-24 16:13:29

Pippogeek (30 views)
2014-09-24 16:12:22

Pippogeek (19 views)
2014-09-24 16:12:06

Grunnt (45 views)
2014-09-23 14:38:19

radar3301 (28 views)
2014-09-21 23:33:17

BurntPizza (63 views)
2014-09-21 02:42:18

BurntPizza (33 views)
2014-09-21 01:30:30

moogie (41 views)
2014-09-21 00:26:15

UprightPath (50 views)
2014-09-20 20:14:06

BurntPizza (54 views)
2014-09-19 03:14:18
List of Learning Resources
by Longor1996
2014-08-16 10:40:00

List of Learning Resources
by SilverTiger
2014-08-05 19:33:27

Resources for WIP games
by CogWheelz
2014-08-01 16:20:17

Resources for WIP games
by CogWheelz
2014-08-01 16:19:50

List of Learning Resources
by SilverTiger
2014-07-31 16:29:50

List of Learning Resources
by SilverTiger
2014-07-31 16:26:06

List of Learning Resources
by SilverTiger
2014-07-31 11:54:12

HotSpot Options
by dleskov
2014-07-08 01:59:08
java-gaming.org is not responsible for the content posted by its members, including references to external websites, and other references that may or may not have a relation with our primarily gaming and game production oriented community. inquiries and complaints can be sent via email to the info‑account of the company managing the website of java‑gaming.org
Powered by MySQL Powered by PHP Powered by SMF 1.1.18 | SMF © 2013, Simple Machines | Managed by Enhanced Four Valid XHTML 1.0! Valid CSS!