Java-Gaming.org Hi !
Featured games (83)
games approved by the League of Dukes
Games in Showcase (538)
Games in Android Showcase (132)
games submitted by our members
Games in WIP (600)
games currently in development
News: Read the Java Gaming Resources, or peek at the official Java tutorials
 
   Home   Help   Search   Login   Register   
  Show Posts
Pages: [1] 2
1  Game Development / Game Mechanics / Re: Resource Loading manager. Onto memory or not? on: 2013-01-14 22:13:32
Ok, I took another look at it and I modified the function to handle sprite sheets.  It's not perfect, but it works well enough for me:

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  
public BufferedImage getImage(String imageName, int row, int col, int width, int height){
      SoftReference<BufferedImage> ref = imageCache.get(imageName+row+col);
     
      if(ref == null){
         BufferedImage img = null;
         try{
            img = ImageIO.read(new File("src/images/" + imageName + ".png"))
                  .getSubimage(col*width, row*height, width, height);
         } catch (IOException ex){
            //handle exception
            System.out.println("src/images/" + imageName + ".png");
            System.out.println(ex.getMessage());
         }
         
         imageCache.put(imageName+row+col, new SoftReference<BufferedImage>(img));
         return img;
      }else{
         //we've stored this image before
         BufferedImage img = ref.get();
         if(img != null){
            return img;
         }else{
            imageCache.remove(imageName+row+col);
            return getImage(imageName, row, col, width, height);
         }
      }
   }


Here, you have to give it a row, column, width of the image, and height of the image.  I went ahead and said "give it a sprite sheet and a location on the sheet, if it can't find it, it loads the sheet, cuts the image out, and saves it back into the image cache".

Bad news is that you have to keep track of the row/column of the animation you need.  I have an animation class that handles it currently, but as far as the resource handler is concerned, there you go.
2  Game Development / Game Mechanics / Re: Resource Loading manager. Onto memory or not? on: 2013-01-10 17:27:21
Kaffiene, that's a pretty cool implementation, but does this make it more difficult to deal with sprite sheets?  It seems, if you want to deal with an animation with multiple frames, this would have to be modified a bit.
3  Game Development / Newbie & Debugging Questions / Re: Applet - Illegal URL Redirect on: 2013-01-08 20:47:58
So I just downloaded a java update, and now it seems to be working again. What the hell's going on?  Clueless
4  Game Development / Newbie & Debugging Questions / Re: Applet - Illegal URL Redirect on: 2013-01-04 21:53:07
Welp, at least i'm not the only person getting the error in this thread. Tongue

I'm looking into it as best I can, but I really don't know where to start.  I suppose I can upload my code if anyone's interested in looking at it.
5  Game Development / Newbie & Debugging Questions / Re: Applet - Illegal URL Redirect on: 2013-01-03 21:51:55
I have no idea what that does, either.  I just know that when I downloaded jre 1.7 update 10, i started recieving these errors.  I think it's the same for jre 6 update 29 and up. Right now I'm running the latest version of jre 6.
6  Game Development / Newbie & Debugging Questions / Re: Applet - Illegal URL Redirect on: 2013-01-03 21:03:56
I can make that change.  Do you have the latest versions of jre 1.7 installed?
7  Game Development / Newbie & Debugging Questions / Re: Applet - Illegal URL Redirect on: 2013-01-03 20:04:32
I checked into this error some more and it looks like my applet is violating the Same-Origin policy.  This makes sense because this wasn't an issue until I had updated java to the latest version of 1.7.  I don't know how my applet is actually violating this policy, however.  Everything in the applet comes out of the jar, which is hosted at michaelfearing.com/BalloonPopper.html.  As far as I know, it's not trying to access any other site.  What's going on here and why is it so hard to explain to me! Cranky



https://nealpoole.com/blog/2011/10/java-applet-same-origin-policy-bypass-via-http-redirect/
8  Game Development / Newbie & Debugging Questions / Applet - Illegal URL Redirect on: 2012-11-06 21:20:37
Well ladies and gents, I haven't posted in a while because I had to get something finished and out there.  It's terribad, but I did it:

ginger.geekwagon.net/BalloonPopper.html

My problem is that, while it works in the above url (at least for myself and my friends), it does NOT work on my brand-new domain:

michaelfearing.com/BalloonPopper.html

Now, before anyone mentions "it seems to work for me!", I did notice that the first time I gave it a try, I had no problems.  But all subsequent times, I was given an illegal URL redirect error.  Does anyone know why this is?  I can't seem to narrow it down, and most suggestions online seem to suggest I'm trying to redirect to another site, which I'm not.  The only "redirect" i can even think of would be that inside the jar file, there is a folder for all of my images.  Would that cause it?

I can email the source code if anyone wants to take a look.  That being said, you'll probably have to work through some ugly code. :\
9  Game Development / Game Play & Game Design / Re: your turn / my turn logic on: 2012-02-08 21:24:22
Srsly gais, this is really helpful.  Also, this implementation seems like it would make sense to have a state manager class. in between the various states and the game class that holds the changeState(State state) method.
10  Game Development / Game Play & Game Design / Re: your turn / my turn logic on: 2012-02-07 15:24:44
1  
2  
3  
4  
    public interface State extends KeyListener, MouseListener, MouseMotionListener{
        public void next(Graphics g);   //I'm not allowed to call it Update for some reason  :(
        //Probably because of a collision with the built in function in Swing with the same name
    }

And then just register the current state as a listener and you won't have to pass events through to the current state in your state handling code.  Wink



EDIT: Also, I'm assuming this, but it makes the most sense to me:

I have a canvas that I'm adding my listeners to.  When you say register, then when we change states, we'll have to remove the current state's listeners from the canvas, change the state, then add the new state's listeners to the canvas, right?
11  Game Development / Game Play & Game Design / Re: your turn / my turn logic on: 2012-02-06 22:21:26
Should each state implement its own key listener, or is that a bad idea?
12  Game Development / Articles & tutorials / Re: Game loops! on: 2012-01-19 18:51:57
So I noticed when I added 15 instead of 10 to the sleep on the variable timestep, it didn't error out on me.  Did it error out on anyone else?

The error was that the time to sleep was a negative value, but it look like it's only for the first time the loop runs.  Every time after that it's between 8 and 10.  Any ideas?
13  Game Development / Newbie & Debugging Questions / Re: Collision detection between player and an object on: 2011-12-28 19:50:05
When you're dealing with a 2d array for your map, it may help think of it in terms of rows and columns, not x and y.  In that instance, y = the rows (because they're vertical) and x = the columns (because they're horizontal), which REALLY tripped me up when displaying my tile map in the game I'm making, because it seems completely backwards.

Just something to keep in mind.
14  Games Center / WIP games, tools & toy projects / Re: Flesh Snatcher on: 2011-12-09 14:47:12
I dunno why, but I kind of get a Timesplitters vibe from those screens.

I miss timesplitters. Sad
15  Game Development / Newbie & Debugging Questions / Re: How to search a text file?! Please help! on: 2011-11-17 22:04:15
If you're already reading the file line-by-line, you can use a string tokenizer to separate the username and password:

1  
2  
3  
4  
 StringTokenizer st = new StringTokenizer("this is a test");
     while (st.hasMoreTokens()) {
         System.out.println(st.nextToken());
     }


Output:

this
is
a
test

Just replace "this is a test" with the nextline read and you can parse out the username and password to do individual checks on them.
16  Game Development / Newbie & Debugging Questions / Re: Rotating a Rectangle object on: 2011-11-16 20:47:04
My brain hurts.

So here's my progress: I've managed to draw what I want on the screen using a global AffineTransform (i named it identity in the code below) that holds the default transform so that the screen doesn't go all out of whack, but the collisions that occur behind the scenes don't match what I've drawn.  For reference, another screenshot here where the red rectangle surrounding the bullet is what I want to check collisions with, while the blue rectangle is what collisions are actually checked with.



Here's some of the code for drawing what I want:

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  
AffineTransform transform = new AffineTransform();
      Polygon poly;
      for(int i = bullets.size() - 1; i >= 0; i--){
         
         if (bullets.get(i).getX() < 0 || bullets.get(i).getX() > screenWidth ||
            bullets.get(i).getY() < -30 || bullets.get(i).getY() > screenHeight ||
            !bullets.get(i).isAlive())
         {
            bullets.remove(i);
         }else{
            bullets.get(i).update(elapsedTime);
            int[] xpoints = {(int)bullets.get(i).getX(), (int)bullets.get(i).getX() + 30, (int)bullets.get(i).getX() + 30, (int)bullets.get(i).getX()};
            int[] ypoints = {(int)bullets.get(i).getY(), (int)bullets.get(i).getY(), (int)bullets.get(i).getY() + 16, (int)bullets.get(i).getY() + 16};
           
            poly = new Polygon(xpoints, ypoints, 4);
                       
            transform.setToTranslation(bullets.get(i).getX(),
               bullets.get(i).getY());
            transform.rotate(bullets.get(i).theta());
            g2d.setTransform(identity);
            g2d.drawImage(bullets.get(i).getImage(), transform, null);
            g2d.setColor(Color.RED);
            g2d.rotate(bullets.get(i).theta(), bullets.get(i).getX(), bullets.get(i).getY());
            g2d.draw(poly);
                       
         }
      }


And here's the code I'm using for collision detection:

1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
24  
public void checkCollisions(){
      for(int i = 0; i < zombies.size(); i++){
         //check collision with bullet
         Rectangle zombie = new Rectangle((int)zombies.get(i).getX(), (int)zombies.get(i).getY(),
            zombies.get(i).getWidth(), zombies.get(i).getHeight());
           
           
         for(int j = 0; j < bullets.size(); j++){
            Rectangle bullet = new Rectangle((int)bullets.get(j).getX(), (int)bullets.get(j).getY(),
               bullets.get(j).getWidth(), bullets.get(j).getHeight());
           
            if(bullets.get(j).isAlive() && zombie.intersects(bullet)){
               
               bullets.get(j).setAlive(false);
               zombies.get(i).setAlive(false);
           
            }
         }
         
         if(zombie.intersects(new Rectangle((int)player.getX(), (int)player.getY(), player.getWidth(), player.getHeight()))){
            //do something to the player
         }
      }
   }


I'm not sure how to go forward because i've only transformed the image; i think the polygon needs to have those dimensions itself instead of being transformed.
17  Game Development / Newbie & Debugging Questions / Re: Rotating a Rectangle object on: 2011-11-16 15:43:50
Yes you would have to use Area for this. The easiest way would be to put a Polygon into the Area. Then do a cheap bounding rectangle v. rectangle check before you do an Area check since the intersect(Area) method of Area is slooooow.

I'm going to try this solution first.

I've never used an area object, but the docs say that every area object has a getBounds() method that returns a rectangle that completely encases the area.  So if I'm reading you correctly, I'd create an area around each bullet, then use the area object's getBounds() to cheaply test for a collision.  If a collision is found, we test further to see if the actual area is colliding as well?
18  Game Development / Newbie & Debugging Questions / Re: Rotating a Rectangle object on: 2011-11-15 22:37:49
I've just run into a situation that's really similar to this one.  It's really bugging me as to how I can't seem to rotate the rectangle to match the image that the rectangle is based on.  The image just uses a transform to rotate.  i've tried messing around with Graphics2D's rotate for the rectangle and holy hell that swirls the entire screen into oblivion. 

Here's a screenshot as an example of my woes:



So I'm supposed to use a shape object instead of a rectangle to work with collision detection?  I'm just wondering how to get the rectangle to match up with the bullet, basically.
19  Game Development / Articles & tutorials / Re: Basic Game on: 2011-10-27 13:57:35
Yeah, I found that sketch online and it fits in so many situations.

After changing the Ms to ms, everything worked just fine and I could access the booleans I created using an instance of the class that I've added to the canvas.  Thanks guys!
20  Game Development / Articles & tutorials / Re: Basic Game on: 2011-10-26 21:44:37
 Huh

 Undecided

 Cranky

 Angry

21  Game Development / Articles & tutorials / Re: Basic Game on: 2011-10-26 20:55:26
Gudradain, any thoughts on why those mouse click events aren't firing off?
22  Game Development / Articles & tutorials / Re: Basic Game on: 2011-10-26 16:44:33
It's added to the canvas in the Game() method in the original code, but not to the frame.
23  Game Development / Articles & tutorials / Re: Basic Game on: 2011-10-26 16:24:57
Sorry for double-post.

I stopped trying to derive a class from your Game class, but that nested class still gets me.  I've put system print lines in the MouseControl class to see when an event is being registered, and it doesn't look like it's ever getting there.  What am I missing?

Here's the code that I've changed/added:

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  
private class MouseControl extends MouseAdapter{
     
      public boolean mouseLeftPressed, mouseRightPressed;
     
      public void MouseClicked(MouseEvent e){}
      public void MouseDragged(MouseEvent e){}
      public void MouseEntered(MouseEvent e){}
      public void MouseExited(MouseEvent e){}
      public void MouseMoved(MouseEvent e){}
      public void MousePressed(MouseEvent e){
         switch(e.getButton()) {
            case MouseEvent.BUTTON1:
               mouseLeftPressed = true;
               System.out.println("mouseLeftPressed");
               break;
            case MouseEvent.BUTTON2:
               mouseRightPressed = true;
               System.out.println("mouseRightPressed");
               break;
         }
      }
      public void MouseReleased(MouseEvent e){
         switch(e.getButton()) {
            case MouseEvent.BUTTON1:
               mouseLeftPressed = false;
               System.out.println("mouseLeftReleased");
               break;
            case MouseEvent.BUTTON2:
               mouseRightPressed = false;
               System.out.println("mouseRightReleased");
               break;
         }
      }
      public void MouseWheelMoved(MouseEvent e){}
     
   }
24  Game Development / Articles & tutorials / Re: Basic Game on: 2011-10-25 19:55:35
His update() and render(g) methods say to override them in a subclass, so it looks like it's meant to be extended.

EDIT: Although the more i look at it, the more I think you are right.  It doesn't seem like it needs to be derived from.  I'll give it a try without a subclass and see if that works better or not.
25  Game Development / Articles & tutorials / Re: Basic Game on: 2011-10-25 19:32:46
I've extended your game class, but I'm having trouble understanding how to access the MouseControl nested class.  I think this is just my limited understanding of java, but if a nested class is declared private, I don't understand how i access it from the derived class.  I'm not supposed to modify it in the superclass, right?  That would defeat the purpose of deriving it in the first place.

Halp? Sad
26  Game Development / Newbie & Debugging Questions / Re: Clunky Sprite Movement on: 2011-09-29 16:53:54
Oh wow.  I changed the movement buttons to WASD and that fixed the problem.  I didn't know keyboards carried such a random limitation.  Thanks guys!
27  Game Development / Newbie & Debugging Questions / Re: Clunky Sprite Movement on: 2011-09-28 21:12:27
I agree, IE is terrible.  But I was at work when I posted this and I can't use any other browser. Sad

I've commented out the contents of the keytyped event (not sure why it's even there in the first place, actually) and that didn't change the behavior. Aazimon, I did put this line in the handleMovement function:

1  
if(keySpacePressed && keyUpPressed && keyLeftPressed){System.out.println("up/left/space pressed");}


And it very seldom fired off.  I had to hold space and spam button presses on up and left to get anything to print out.  If I hold the buttons, "up/left/space pressed" never prints out.
28  Game Development / Newbie & Debugging Questions / Re: Clunky Sprite Movement on: 2011-09-28 19:38:01
I was going to start a new topic for this, but this seems like a good place to put this issue even though it's an old topic, so bumping for great justice.

I'm having an issue that I can't quite pin down, and it's keeping my player from being able to move along the x and y axis at the same time while firing.  Basically, it's like this: if the up arrow key is pressed and the left arrow key is pressed, then the space key being pressed doesn't register.  If the space and left arrow keys are pressed, then the up arrow key doesn't register.  If the space and up arrow keys are pressed, then the left arrow key doesn't register.

I can press any combination of up/right/space, down/right/space, or down/left/space.  It only seems to be the combination of up/left/space that's causing problems.

Here's my key events:

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  
public void keyReleased(KeyEvent k) {
      int keyCode = k.getKeyCode();
        switch (keyCode) {
         case KeyEvent.VK_LEFT:
            keyLeftPressed = false;
            break;
         case KeyEvent.VK_RIGHT:
            keyRightPressed = false;
            break;
         case KeyEvent.VK_UP:
            keyUpPressed = false;
            break;
         case KeyEvent.VK_DOWN:
            keyDownPressed = false;
            break;
         case KeyEvent.VK_SPACE:
            keySpacePressed = false;
         break;
      }
   }
    public void keyTyped(KeyEvent k) {keyPressed(k);}
    public void keyPressed(KeyEvent k) {
      int keyCode = k.getKeyCode();
        switch (keyCode) {
         case KeyEvent.VK_LEFT:
            keyLeftPressed = true;
            break;
         case KeyEvent.VK_RIGHT:
            keyRightPressed = true;
            break;
         case KeyEvent.VK_UP:
            keyUpPressed = true;
            break;
         case KeyEvent.VK_DOWN:
            keyDownPressed = true;
            break;
         case KeyEvent.VK_SPACE:
               keySpacePressed = true;
            break;
         case KeyEvent.VK_ENTER:
            showBoundingBox = !showBoundingBox;
            break;
      }
   }


Here's the method that handles movement by changing player velocity:

1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
public void handleMovement(){
     
      if(keyUpPressed && keyDownPressed){
         player.setVelocity(new Point((int)player.velocity().getX(), 0));
      }else if(keyUpPressed && player.position().getY() > 31){
         player.setVelocity(new Point((int)player.velocity().getX(), -3));
      }else if(keyDownPressed && player.position().getY() < 430){
         player.setVelocity(new Point((int)player.velocity().getX(), 3));
      } else {
         player.setVelocity(new Point((int)player.velocity().getX(), 0));
      }
     
      if(keyLeftPressed && keyRightPressed){
         player.setVelocity(new Point(0, (int)player.velocity().getY()));
      }else if(keyLeftPressed && player.position().getX() > 9){
         player.setVelocity(new Point(-3,(int)player.velocity().getY()));
      }else if(keyRightPressed && player.position().getX() < 609){
         player.setVelocity(new Point(3, (int)player.velocity().getY()));
      } else {
         player.setVelocity(new Point(0, (int)player.velocity().getY()));
      }  
   }
 

Let me know if any additional information is needed.

Also, as a side note, is there any way to keep code from displaying in impossibly small font?  Thanks!
29  Game Development / Game Mechanics / Re: Asteroids bouncing off each other when they collide. on: 2011-09-09 18:41:04
I'd thought about adding more cases, but that seems like it's just trying to brute force it.  I feel there's probably a more elegant solution.

I'm not sure how this book compares to others.  It's my first for game programming.  It does a well-enough job telling someone how to set up their environment, which was a big deal to me because I've never had to before and most books say something along the lines of "just use netbeans".  This one talks about different text editors and IDEs, as well as how to make sure your command line will understand javac or java without having to type out the entire file path.  The book also shows you how things work in practice more than in theory, which i appreciate.

Also, it was free to me through my work. Smiley
30  Game Development / Game Mechanics / Asteroids bouncing off each other when they collide. on: 2011-09-09 15:40:31
This is an exercise out of Beginning Java SE6 Game Programming, Third Edition by Jonathan S Harbour.

So I'm given an exerice in chapter 6 to take the code given to me (which puts one asteroid sprite on the screen, rotates it, and moves it with a velocity represented by a Point object) and make multiple asteroids moving around on screen.  This part was easy.  The second part was that I was to make the asteroids collide and bounce off of each other.

My first run at this produced many problems.  The first was that the asteroids tended to stick to each other instead of bounce.  I found that this was because of rapidly changing velocities due to two asteroids colliding every single frame and the velocity changing so quickly that they didn't get out of each others way.  So instead of checking for collision, I tried to predict a collision.  For the purposes of the exercise, this works just fine.  It also allowed me to bounce the asteroids off of each other.  But it's not completely accurate.  Here's my code:

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  
import java.awt.*;
import java.awt.image.*;
import javax.swing.*;
import java.awt.event.*;
import java.awt.geom.*;
import java.util.*;
import java.net.*;
import java.lang.Math;

public class MultiSprite extends JFrame implements Runnable, KeyListener {

   int screenWidth = 640;
   int screenHeight = 480;
   
   //double buffer objects
   BufferedImage backbuffer;
   Graphics2D g2d;
   
   int MAX = 5;
   Sprite[] asteroid = new Sprite[MAX];
   
   ImageEntity background;
   Thread gameloop;
   Random rand = new Random();
   
   boolean enterKeyPressed = false;
   
   public static void main(String[] args) {
      new MultiSprite();
   }
   
   public MultiSprite() {
      super("Sprite Test");
      setSize(640, 480);
      setVisible(true);
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
     
      //create the back buffer for smooth graphics
      backbuffer = new BufferedImage(screenWidth, screenHeight, BufferedImage.TYPE_INT_RGB);
      g2d = backbuffer.createGraphics();
     
      //load the background
      background = new ImageEntity(this);
      background.load("bluespace.png");
     
      //load the asteroid sprites
      Point point;
      for (int n = 0; n<MAX; n++){
            asteroid[n] = new Sprite(this, g2d);
         asteroid[n].load("asteroid2.png");
         
         point = new Point(rand.nextInt(600)+20,
            rand.nextInt(440)+20);
         asteroid[n].setPosition(point);
         asteroid[n].setRotationRate(-5 + rand.nextInt(11));
         //asteroid[n].setFaceAngle(rand.nextInt(360));
         //asteroid[n].setMoveAngle(rand.nextInt(360));
         asteroid[n].setAlive(true);
         asteroid[n].setVelocity(new Point(-5 + rand.nextInt(11), -5 + rand.nextInt(11)));
      }
     
      enterKeyPressed = false;
      addKeyListener(this);

        gameloop = new Thread(this);
        gameloop.start();
   }
   
    public void run() {
        Thread t = Thread.currentThread();
        while (t == gameloop) {
            try {
                Thread.sleep(30);
            }
            catch (InterruptedException e) {
                e.printStackTrace();
            }
         
         //if game is paused
         if(!enterKeyPressed){
         
            //draw the background
            g2d.drawImage(background.getImage(), 0, 0, screenWidth-1,
               screenHeight-1, this);

            //draw asteroids  
            for(int n = 0; n < MAX; n++){
               if(asteroid[n].alive()) {
                  //asteroid[n].drawBounds(Color.YELLOW);
                 
                  //warp the asteroid at screen edges
                  if (asteroid[n].position().getX() < -50){
                     asteroid[n].setPosition(new Point(getSize().width + 50, (int)asteroid[n].position().getY()));
                  } else if (asteroid[n].position().getX() > getSize().width + 50){
                     asteroid[n].setPosition(new Point(-50, (int)asteroid[n].position().getY()));
                  }
                 
                  //warp the asteroid at screen edges
                  if (asteroid[n].position().getY() < -40){
                     asteroid[n].setPosition(new Point((int)asteroid[n].position().getX(), getSize().height + 40));
                  } else if (asteroid[n].position().getY() > getSize().height + 40){
                     asteroid[n].setPosition(new Point((int)asteroid[n].position().getX(), -40));
                  }
                 
                  CheckCollisions(n);
                 
                  asteroid[n].updatePosition();
                  asteroid[n].updateRotation();
                  asteroid[n].transform();
                  asteroid[n].draw();
               }
            }
            repaint();
         }
        }
    }
   
   public void CheckCollisions(int n){
      for(int x = 0; x < MAX; x++){
         if(x!=n && PredictCollision(asteroid[n], asteroid[x])){
            //we have predicted collision.
            Rectangle intersectRect = asteroid[n].getBounds().intersection(asteroid[x].getBounds());
           
            //collision on x axis: reverse x velocity
            if(intersectRect.getHeight() > intersectRect.getWidth()){
               asteroid[n].setVelocity(new Point(-1 * (int)asteroid[n].velocity().getX(), (int)asteroid[n].velocity().getY()));
               asteroid[x].setVelocity(new Point(-1 * (int)asteroid[x].velocity().getX(), (int)asteroid[x].velocity().getY()));
            }
           
            //collision on both axis equally: reverse x and y velocity
            if(intersectRect.getHeight() == intersectRect.getWidth()){
               asteroid[n].setVelocity(new Point(-1 * (int)asteroid[n].velocity().getX(), -1 * (int)asteroid[n].velocity().getY()));
               asteroid[x].setVelocity(new Point(-1 * (int)asteroid[x].velocity().getX(), -1 * (int)asteroid[x].velocity().getY()));
            }

            //collision on y axis: reverse y velocity
            if(intersectRect.getHeight() < intersectRect.getWidth()){
               asteroid[n].setVelocity(new Point((int)asteroid[n].velocity().getX(), -1 * (int)asteroid[n].velocity().getY()));
               asteroid[x].setVelocity(new Point((int)asteroid[x].velocity().getX(), -1 * (int)asteroid[x].velocity().getY()));
            }
         }
      }
   }
   
   public boolean PredictCollision(Sprite ast1, Sprite ast2){
      if(Math.abs((ast1.position().getX() + ast1.velocity().getX()) - (ast2.position().getX() + ast2.velocity().getX())) < 60 &&
         Math.abs((ast1.position().getY() + ast1.velocity().getY()) - (ast2.position().getY() + ast2.velocity().getY())) < 60){return true;}
      return false;
   }

    public void paint(Graphics g) {
        //draw the back buffer to the screen
        g.drawImage(backbuffer, 0, 0, this);
    }

   //handle keyboard events
    public void keyReleased(KeyEvent k) {}
    public void keyTyped(KeyEvent k) {}
    public void keyPressed(KeyEvent k) {
      switch(k.getKeyCode()){
         case KeyEvent.VK_ENTER:
            enterKeyPressed = !enterKeyPressed;
            break;
      }
   }
     
}


The two main methods to look at here are CheckCollisions and PredictCollision.  Notice how I'm just reversing velocities.  This seems to work ok except in instances where two asteroids are moving in the same direction,  but the one in front is moving slower than the one behind it.  When they collide, they both change course to move in the opposite direction whereas the one in front should get a boost and the one in back should slow down.

Does anyone have a better means of implementing this?  My best guess is that vector math is probably the route to go here.

Edit: I should note that the Sprite class used here contains the velocity valuesas well as a move angle and a face angle.  So I have both a speed and direction.
Pages: [1] 2
 

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

The first screenshot will be displayed as a thumbnail.

rwatson462 (28 views)
2014-12-15 09:26:44

Mr.CodeIt (19 views)
2014-12-14 19:50:38

BurntPizza (35 views)
2014-12-09 22:41:13

BurntPizza (70 views)
2014-12-08 04:46:31

JscottyBieshaar (32 views)
2014-12-05 12:39:02

SHC (44 views)
2014-12-03 16:27:13

CopyableCougar4 (40 views)
2014-11-29 21:32:03

toopeicgaming1999 (108 views)
2014-11-26 15:22:04

toopeicgaming1999 (94 views)
2014-11-26 15:20:36

toopeicgaming1999 (29 views)
2014-11-26 15:20:08
Understanding relations between setOrigin, setScale and setPosition in libGdx
by mbabuskov
2014-10-09 22:35:00

Definite guide to supporting multiple device resolutions on Android (2014)
by mbabuskov
2014-10-02 22:36:02

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
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!