I have been racking my brain trying to figure out what is wrong with my collision detection, and I know it is something extremely simple that I am just not seeing, so maybe someone here can shed some light on it for me.
I have created this app that generates two rectangles, then checks for collision. When a collision occurs, the moving rectangle bounces off the other. Everything works great if I am moving around by only pressing one key at a time, but if I am holding down two opposite movement keys (w and s, or a and d) at the point where the two rectangle collide, the rectangles pass through one another.
I hope I've made myself clear. Thanks for any help
/* * To change this template, choose Tools | Templates * and open the template in the editor. */
Welcome to JavaRanch, and welcome to the wonderful world of multithreading!
So the basic idea is this: when the little box hits the big box, you switch the speed to -5. Then below that, you adjust the position based on the speed and on the current direction. This is the right thing to do if the little box is still moving in the direction is was when it hit. But key events can come in at any time. If you carefully time it so that, for example, you hit while going up, but then immediately press "down", then that negative speed is going to make the box go in the direction is was already going -- up into the big box!
I will sit and wait until you get that straight in your head.
OK, all clear?
The best way to fix this would be have an x velocity and a y velocity, and have the keyboard events and the hit detector both change those as needed, instead of having the UP, DOWN, etc constants. That would get rid of the "double negative" problem you're having here.