I have checked out the following link:
http://www.ehow.com/how_12134402_detect-rectangle-collision-java.html
I have made the 2 rectangles around my player and house but am confused about what my if statement should look like, I have a boolean set on x meaning if my rectangles intersect x will return true so I know I start with
if(x=true){
//what to type in here for my collision?
}
This collision is required for my 2D state change game, I have a player that moves around with key inputs and a house on the map, I want my player not to be able to walk through the house.
Thank you in advance.
use Rectangle2D.Double rect = new Rectangle2D.Double(x,y,w,h)) to define your collision box.
Then check
rect.contains(x,y);
or
bool isCollision = rectOne.intersects(rectTwo);
Or more complete example
// returns true at the first collision
// returns false if no collision with none of the houses
Rectangle2D.Double player = new Rectangle2D.Double(x,y,w,h);
Rectangle2D.Double[] houses = map.getHouseBounds();
boolean isAnyCollision = false;
int i = 0;
while (!isAnyCollision && cnt < houses.length) {
isAnyCollision = player.intersects(houses[i]);
}
return isAnyCollision;
Related
I have an if statement which checks for collision as such:
if (BallY == y && BallX == x) // check for collision
{
x = 80; // reset x to initial
y = 240; // reset y to initial
z = 100; //reset z to initial
}
I have a for loop inside this if statement as such:
if (BallY == y && BallX == x) // check for collision
{
x = 80; // reset x to initial
y = 240; // reset y to initial
z = 100; //reset z to initial
for (int i=50; i<width; i+=80)
{
fill(250,0,0);
ellipse(i, 50, 70, 70);
}
}
So the point is to draw a line of circles on the top of the screen once the collision occurs. This code however, only draws them for a split second then they disappear. How would I make them stay given that a collision has occurred?
You might want to use a boolean value that tracks whether the ball has collided. Set it to true when you detect a collision, and then check the value to decide what to draw. Here's a simplified example:
boolean drawRed = false;
void draw() {
if (mouseY > height/2) {
drawRed = true;
}
if (drawRed) {
background(255, 0, 0);
}
}
This code draws a gray background by default, but then turns to red if the mouse goes in the lower half of the window. It stays red even if you move the mouse back to the top part.
This is just a simple example, but the idea is the same: use a variable to track the state of the sketch, set that variable when your condition is met, and check that variable to decide what to draw.
By the way, your collision detection is a little bit suspicious. You probably don't want to check whether the ball is at an exact location. Instead you probably want to check whether the ball overlaps some area. Here is a guide on collision detection in Processing that might be useful.
If you still can't get it working, please narrow your problem down to a MCVE instead of posting disconnected snippets or your full sketch. Good luck!
Did a lot of googling but was not able to solve this problem.
I want to generate n Number rectangles and draw them on a screen. X,Y are generated randomly and the width and height are based on the font size. My goal is to draw a n number of words on a screen positioned randomly without overlapping existing rectangle. I am using Rectangle for collision detection.
private List<Rectangle> rectList = new ArrayList<Rectangle>();
public boolean checkForCollision(Rectangle r) {
boolean collision = false;
if (rectList.size() == 0) {
rectList.add(r);
System.out.println("Adding First");
return collision;
} else {
// loop through the list
Rectangle currRectangle;
for (int i = 0; i < rectList.size(); i++) {
currRectangle = rectList.get(i);
if (r.intersects(currRectangle)) {
System.out.println(r.toString());
System.out.println(currRectangle.toString());
System.out.println("=========================");
return collision;
}
}
System.out.println("No collision");
rectList.add(r);
return !collision;
}
}
This is what I have done to create rectangle and draw a word on it. I am using a loop here.
int width = graphics.getFontMetrics().stringWidth(temp.getWord());
int height = graphics.getFontMetrics().getHeight();
Rectangle newRectangle = new Rectangle(rand.nextInt(1250)+1, rand.nextInt(650)+1, width, height);
int xCordinate = (int)newRectangle.getX();
int yCordinate = (int) newRectangle.getY();
while(collisonChecker.checkForCollision(newRectangle)){
//newRectangle = new Rectangle(rand.nextInt(1250)+1, rand.nextInt(650)+1, width, height);
newRectangle.setLocation(rand.nextInt(1250)+1,rand.nextInt(650)+1);
collisonChecker.checkForCollision(newRectangle);
}
graphics.drawRect((int)newRectangle.getX(), (int)newRectangle.getY(), (int)newRectangle.getWidth(), (int)newRectangle.getHeight());
newRectangle.setLocation(rand.nextInt(1250)+1,rand.nextInt(650)+1);
graphics.drawString(temp.getWord().trim(), (int)newRectangle.getX(),(int)newRectangle.getY() );
You Never change your return value. No matter, if there's a collision or not , the method returns false. set your return value to true idle there's a collision in the for-loop , that should fix the problem
I hope that helped at least a bit
Okay, so this seems "weird" to me...
while(collisonChecker.checkForCollision(newRectangle)){
//newRectangle = new Rectangle(rand.nextInt(1250)+1, rand.nextInt(650)+1, width, height);
newRectangle.setLocation(rand.nextInt(1250)+1,rand.nextInt(650)+1);
collisonChecker.checkForCollision(newRectangle);
}
graphics.drawRect((int)newRectangle.getX(), (int)newRectangle.getY(), (int)newRectangle.getWidth(), (int)newRectangle.getHeight());
newRectangle.setLocation(rand.nextInt(1250)+1,rand.nextInt(650)+1);
graphics.drawString(temp.getWord().trim(), (int)newRectangle.getX(),(int)newRectangle.getY() );
You create a new Rectangle, you check for a collision and start looping while it's true, in the loop you change the location of the of the Rectangle and check the for a collision but ignore the return result ...? But that's not the worse part...
Once the loop finishes, you randomly generate a new location of Rectangle, completely ignoring all the work you did in the loop ...?
Perhaps you should do something more like...
while(collisonChecker.checkForCollision(newRectangle)){
newRectangle.setLocation(rand.nextInt(1250)+1,rand.nextInt(650)+1);
}
graphics.drawRect((int)newRectangle.getX(), (int)newRectangle.getY(), (int)newRectangle.getWidth(), (int)newRectangle.getHeight());
graphics.drawString(temp.getWord().trim(), (int)newRectangle.getX(),(int)newRectangle.getY() );
i'm quite stuck. Before I do anything, heres the code:
if(inAir&&!falling&&!jumping){
if(py<600){
if (!(isBlocked(xminusd, py) || isBlocked(xminus, py + 32 - 1))) {
falling=true;
}else{
py-=2;
inAir=false;
}
}
}
for(int g = 0;g<Map.r.size();g++){
if(rect.intersects(Map.r.get(g))||Map.r.get(g).contains(rect)||rect.contains(Map.r.get(g))||Map.r.get(g).intersects(rect)){
System.out.println("Intersecting!");
inAir= false;
hasjumped=false;
onPlat = true;
falling = false;
jumping = false;
py-=4;
break;
}else{
onPlat = false;
if(inAir==false&&!onPlat){
inAir = true;
onPlat = false;
}
}
}
Now the problem is, i'm trying to make collision detection with a certain type of tile, by creating rectangles for each tile, and if the player collides with it it stops all movement.(falling wise at least). But i've run into a problem. I've used an array list, to create all my rectangles, and i'm using a for loop to check each rectangle. Problem is, if it checks a rectangle and i'm not colliding with that rectangle currently, it immidiatly starts falling, then resetting, because it finds the rectangle i'm colliding with. The problem is im using a for loop to cycle through each rectangle... I'm really stuck on how to do collision detection with platform tiles. Anyone have any help to provide? Please be descriptive.
It doesn't look like it matters which rectangle you are colliding with so try abstracting by making a function that returns true or false if it is colliding with any block and put that in your else if statement. that way if you are still colliding it wont start falling while cycling through the rest of your blocks
Something like
...
if(colliding())
{
//stop falling
}
else
{
//start falling
}
....
boolean colliding(){
for(int g = 0;g<Map.r.size();g++){
//check for collision if true return true
}
return false;
}
EDIT:
The reason this works is because as you are going through the for loop it keeps the object falling while it determines that it should stop. By moving the falling logic away from the collision logic we can determine if it is colliding and then take the appropriate action.
The thing is that i'm helping a friend with a java project for the universty, and we have to create a remake of MSX's Knightmare. The game is pretty developed already but we don't know how to create the collision with the scenary's stuff, like the columns and the bridge over the river. In order to do this i thought that we could just create a logical "grid-mapping" over the png (the whole level is this image, invoked on the game like a plain image) and do the logic on it, just a boolean logic.
So the basic way, that i suggest to do, is a 2D array with this grid calculated on our minds. Is there some tool that we could use in order to do this easier or automated somehow?
Knightmare original version video
And this is the image that we are using on the game
I am going to try answering the title question, which seemed like the important one.
I wrote a little platform game in Java some time ago, and there I wrote a method called comprobarColisiones() (check collisions) which I call everytime
// Check collisions
comprobarColisiones();
h.mover(pasadas); //Move hero
// Moving enemies
if (h.x > en.getX()){
en.mover(h.getdx(), h.getIzq(),pasadas);
}
if (h.x> en2.getX()){
en2.mover(h.getdx(), h.getIzq(),pasadas);
}
// Moving static objects (rocks)
roca1.mover(h.getdx(),h.getIzq());
roca2.mover(h.getdx(),h.getIzq());
roca3.mover(h.getdx(),h.getIzq());
// REPAINTING
repaint();
// A time calculation that I use to control the game speed somewhere
tiempoAnteriorTipito = System.currentTimeMillis();
When I mean "static objects" it's just to differentiate objects with self-movement with those that just scroll as long as the hero moves, in your game (as in mine's) there probably will not be any static object (well, probably the scores and stuff), even rocks will scroll.
public void comprobarColisiones(){
// Getting bounds
Rectangle r1 = en.getBounds();
Rectangle r2 = en2.getBounds();
Rectangle rec_roca1 = roca1.getBounds();
Rectangle rec_roca2 = roca2.getBounds();
Rectangle rec_roca3 = roca3.getBounds();
// Getting bounds and resolving collisions with shooting objects
ArrayList martillos = Heroe.getMartillos();
for (int i = 0; i < martillos.size(); i++) {
Martillo m = (Martillo) martillos.get(i);
Rectangle m1 = m.getBounds();
if (r1.intersects(m1) && en.vive())
{
en.setVive(false);
m.visible = false;
}
else if (r2.intersects(m1)&& en2.vive())
{
en2.setVive(false);
m.visible = false;
}
}
// Checking if hero touches enemies
Rectangle heroecuad = h.getBounds();
if (heroecuad.intersects(r1)&&en.vive()){
perdio = true;
System.out.println("PERDIO CON EL ENEMIGO 1");
}
if (heroecuad.intersects(r2)&&en2.vive()){
perdio = true;
System.out.println("PERDIO CON EL ENEMIGO 2");
}
// Checking if hero touches static objects
if(heroecuad.intersects(rec_roca1)){
System.out.println("CHOCO ROCA 1");
}
if(heroecuad.intersects(rec_roca2)){
System.out.println("CHOCO ROCA 2");
}
if(heroecuad.intersects(rec_roca3)){
System.out.println("CHOCO ROCA 3");
}
}
I created enemies and static stuff and placed them when I load the escenario, just like this:
en = new Enemigo(800, ALTURA_PISO+8);
en2 = new Enemigo(900, ALTURA_PISO+8);
roca1 = new Roca(1650, ALTURA_PISO+17);
roca2 = new Roca(2200, ALTURA_PISO+17);
roca3 = new Roca(3400, ALTURA_PISO+17);
// Being the first number the initial X-Pos and the second the initial Y-Pos, this will change everytime the hero moves, of course
Probably in your game, you'll define any area of the map as explorable, and add some ghost objects to check intersection with the hero and stop his movement. For what I could see, water and columns should NOT be explorable by your hero.
Hope this would give you some ideas.
I'm making a game where i need to give my objects collision, but i have many fast small objects and normal collision algorithms (Intersection of shapes and such) do not work, because the position+speed iteration advances the walls and there's never actually an Intersection.
So i've started constructing my own (Maybe it already exists but i didnt see it anywhere) collision algorithm based on saving the last position the object was.
Please see the following image:
The idea is demonstrated in frame 1 and 2 of the image. Basicly by checking if there's a wall between the left side of the last rectangle and the right side of the new rectangle, i never skip zones while i check collision, and there's no risk of skipping a wall (so i thought).
This is the code of the algorithm:
private void bounce(GameElement b, Terrain t)
{
Rectangle tR = t.getRectangle();
int tRleft = tR.x;
int tRright = tR.x+tR.width;
int tRup = tR.y;
int tRdown = tR.y+tR.height;
Rectangle bRnow = b.getRectangle();
int bRnowLeft = bRnow.x;
int bRnowRight = bRnow.x+bRnow.width;
int bRnowUp = bRnow.y;
int bRnowDown = bRnow.y+bRnow.height;
Rectangle bRlast = b.getRectangleLast();
int bRlastLeft = bRlast.x;
int bRlastRight = bRlast.x+bRlast.width;
int bRlastUp = bRlast.y;
int bRlastDown = bRlast.y+bRlast.height;
boolean leftRight = false, rightLeft=false, upDown=false, downUp=false;
boolean betweenX = false, betweenY = false;
if(bRnow.x>bRlast.x)leftRight=true;
if(bRnow.x<bRlast.x)rightLeft=true;
if(bRnow.y>bRlast.y)upDown=true;
if(bRnow.y<bRlast.y)downUp=true;
if(bRlastRight>tRleft && bRlastLeft<tRright) betweenX = true;
if(bRlastDown>tRup && bRlastUp<tRdown) betweenY=true;
if(leftRight)
if((tRleft>bRnowLeft || tRleft>bRlastLeft) && tRleft<bRnowRight && betweenY)
{
b.setX(tR.x-bRnow.width - 1);
}
if(rightLeft)
if((tRright<bRnowRight || tRright<bRlastRight) && tRright>bRnowLeft && betweenY)
{
b.setX(tR.x+tR.width + 1);
}
if(upDown)
if((tRup>bRnowUp || tRup>bRlastUp) && tRup<bRnowDown && betweenX)
{
b.setY(tR.y-bRnow.height - 1);
}
if(downUp)
if((tRdown<bRnowDown || tRdown<bRlastDown) && tRdown>bRnowUp && betweenX)
{
b.setY(tR.y+tR.height + 1);
}
}
Its called bounce because its not really organized atm, i still have to think how to structure the algorithm so it becomes more generalized and pratical (Would appreciate help on that too)
This way of doing collision has one bug at the moment which is seen in image 3 (sorry for drawing circles, they are supposed to be squares) because FAST objects still pass diagonals :/ On the other hand, direct hits on walls are pretty neat.
How could i improve, optimize and organize this algorithm? Or is there any better algorithm and im just thinking too much for nothing? I appreciate your help.
Axis aligned bounding box trees are usually well suited to detecting object collisions. Here is a tutorial with some code - its examples are for 3D collision detection, but the data structure can be easily adapted to 2D collision detection.