Java Game - Collision Detection for walls using rectangles - java

Im developing a java game im trying to do collision detection right now with my tile map but it is not working how I would like it to. I have made 4 rectangles on the character. One on the top, bottom, left and right side. The rectangles are all 2 times the velocity in width.
To check if the rectangle intersects with the rectangle on the tiles, I use this code
if(LeftSide.intersects(Map.colRect[i])){
MovingLeft = false;
x_pos+=vel;
}
To define the rectangle I use this code
LeftSide = new Rectangle(x_pos,y_pos+(vel*2),(vel*2),spriteHeight-1-(vel*4));
RightSide = new Rectangle(x_pos+spriteWidth-1,y_pos+(vel*2),(vel*2),spriteHeight-(vel*4)-1);
UpSide = new Rectangle(x_pos+(vel*2),y_pos,spriteWidth-(vel*4)-1,(vel*2));
DownSide = new Rectangle(x_pos+(vel*2),y_pos+spriteHeight-1,spriteWidth-(vel*4)-1,(vel*2));
What happens is when the player hits the wall, goes into the wall as much as the velocity, and then gets pushed back out of the wall the amount of the velocity. This results in the character to just go back and forth making a blurry motion whenever you hit a wall and hold down the key.
Is there an algorithm I could use to fix this? or a different method?
The rectangles on the character look like this:
Any help would be greatly appreciated. I really want to fix this
Thanks

You probably want to model elastic collisions, discussed here and illustrated here.

Related

libGDX polygon rebound (bounce) angle

I am hoping someone could point me in the direction of a libGDX example that shows how the rebound angle is calculated when a polygon hits another (which is fixed) - The questions/answers I've found on StackOverflow have all been to general (abstract), I'm hoping for a more libGDX specific answer :)
Currently, I am using Intersector.MinimumTranslationVector to check whether the moving polygon has hit another fixed-stationary polygon and then using the resultant values to shift the objects back out of each other.
When the collision occurs virtually or horizontally, the bounce calculation is easy and currently works well. What I am having troubles with are the diagonal collisions - working out which face was actually hit and the direction in which to bounce.
The moving polygon uses a Vector2 object for it's velocity, so the question is how is the new velocity calculated? I'm assuming it can be done using the Intersector class, but how?

Android translated canvas collision of rectangles

im trying do develop a Zelda like game. So far i am using bitmaps and everything runs smooth. At this point the camera of the hero is fixed, meaning, that he can be anywhere on the screen.
The problem with that is scaling. Supporting every device and keeping every in perfect sized rects doesnt seem to be that easy :D
To prevent that i need a moving camera. Than i can scale everything to be equally sized on every device. The hero would than be in the middle of the screen for the first step.
The working solution for that is
xCam += hero.moveX;
yCam += hero.moveY;
canvas.translate(xCam,yCam);
drawRoom();
canvas.restore();
drawHero();
I do it like this, because i dont wand to rearrange every tile in the game. I guess that could be too much processing on some devices. As i said, this works just fine. the hero is in the middle of the screen, and the whole room is moving.
But the problem is collision detection.
Here a quick example:
wall.rect.intersects(hero.rect);
Assuming the wall was originally on (0/0) and the hero is on (screenWitdh/2 / screenHeight/2) they should collide on some point.
The problem is, that the x and y of the wall.rect never change. They are (0/0) at any point of the canvas translation, so they can never collide.
I know, that I can work with canvas.getClipBounds() and then use the coordinates of the returned rect to change every tile, but as I mentioned above, I am trying to avoid that plus, the returned rect only works with int values, and not float.
Do you guys know any solution for that problem, or has anyone ever fixed something like this?
Looking forward to your answers!
You can separate your model logic and view logic. Suppose your development dimension for the window is WxH. In this case if your sprite in the model is 100x100 and placed at 0,0, it will cover area from 0,0 to 100, 100. Let's add next sprite (same 100x100 dimension) at 105,0 (basically slightly to the right of the first one), which covers area from 105,0 to 205,100. It is obvious that in the model they are not colliding. Now, as for view if your target device happens to be WxH you just draw the model as it is. If your device has a screen with w = 2*W, h = 2*H, so twice as big in each direction. You just multiply the x and y by w / W and h / H respectively. Therefore we get 2x for x and y, which on screen becomes 1st object - from 0,0 to 200, 200, 2nd object - from 210,0 to 410, 200. As can be seen they are still not colliding. To sum up, separate your game logic from your drawing (rendering) logic.
I think you should have variables holding the player's position on the "map". So you can use this to determine the collision with the non changing wall. It should look something like (depensing on the rest of your code):
canvas.translate(-hero.rect.centerX(), -.rect.centerY());
drawRoom();
canvas.restore();
drawHero();
Generally you should do the calculations in map coordinates, not on screen. For rendering just use the (negative) player position for translation.

Java Game Hitbox Detection & Rounded Corners

I am working on a simple 2D game with Java, swing and no framework. I have a rectangular player that the user can move around. On the map are few obstacles which the player should not be able to go through. I did this by making a new Rectangle Object for the player and each obstacle with their bounds. But I’m not really sure if this is the right way to do it. It works but the movements of the player are not really user friendly. If the player wants to pass two obstacles they must be on the perfect coordinates to pass.
Is it even a good idea to check for intersections between the player and the obstacle with a Rectangle object or should I do it another way?
Now for my 2nd question:
I’d like to replace the rectangular hitboxes with the same hitbox but with rounded corners so the player could pass more easily.
This is what the game looks like with hitboxes enabled.
The code that checks if the player and the obstacles have yet intersected:
for (Player p : this.getPlayerArray()) {
Rectangle recPlayer = p.playerBounds();
for (Obstacle kiste : obstacleArray) {
Rectangle recKiste = kiste.obstBounds();
if (recPlayer.intersects(recKiste)) {
p.setX(100); //Not actual code here
}
}
}
The function that returns the hitbox of the player / obstacle:
public Rectangle obstBounds() {
return new Rectangle(this.getX(),
this.getY(), image.getImage().getWidth(null),
image.getImage().getHeight(null));
}
Many years ago I wrote a Khepera simulator as part of my undergrads' final year project. I started by doing collision detection as you are doing, that is intersecting areas... My supervisor made me notice that since the shape of my robot was a circle I just could check if the center of the robot was inside another shape, if that was the case a collision occured.
Your case is even simpler since you move on tiles... so either you do (as suggested in the comments) maintain a set of "move/no move" tiles and check that, or you just check that the position of your player is within, or not, a 'forbidden' rectangle, i.e. an obstacle. If it is, then you have to reset the position of the character to be 'outside' of the obstacle (minus the character's bounding box, obviously)
I strongly suggest to do it the tiles way: allow only up/down/left/right movements and check against a 'forbidden' set of movements given a tile-position. If you really want 'freedom' of movements than go with circles (bounding boxes/circles) because they are easy to reason with, easy to do a position reset (in case of collisions) and perfect for your case (every tile can contain a circle, whether an obstacle or the player.)
There are many ways to go about collision checking, but I think a simple approach would do just fine for your use-case.
First from the looks of your screenshot, a tile is either an obstacle or passable, but never half of each. In that case it would be simplest to just check on which tile the center (or feet, choose what looks best) of the character are.
If its an obstacle, they cant go there, simple as that. Note that this will allow the player to move partially into an obstacle, but many games do it this way and players are certainly used to this behavior, especially in 2D games with graphics designed to look like an isometric projection (which I would yours class as). A variation of this would be to simply make the player collision rectangle smaller (say half a tile, again centered at the player sprites chest or feet).

Collision detection between ball & maze made dynamically from text file

Ok so I am creating a ball tilting game, where you navigate a ball around a maze. The ball works, and is all good in the area however I am having some problems in the maze.
The maze is programmatically created through a .txt file that contains 1's and 0's (1's being walls, and 0's being floor.) I have a for loop that goes through the whole .txt file and places a white(wall) or black(floor) square at the proper coordinates on a canvas. This is similar to the apps-for-android Amazed game if you have seen it link. However, instead of placing wall-type detection on his tiles, he just resets the game and deducts a life point if the user rolls onto a 'void' tile.
However I am looking to have 'walls' and not 'voids'. Where if the ball touches the wall, it doesn't go beyond that point, but can still move freely on the other axis. Unless it hits a corner, of course.
The problem I am having is actually creating this detection. I have tried a number of ways but nothing so far has been successful or useful.
I have tried:
- Have an ArrayList of all of the coordinates of the wall tiles, and every game tick, it checks to see if the ball is touching one. However this just slowed the game down to a crawl and was just extremely terrible.
- Check to see what tile the ball is on, and if it's on a wall tile, to stop it on an axis but let it move freely on the other, however this still didn't work as there were some issues when the ball was to the right of the wall tile, but also under it, it couldnt move up, as the code detected it being under the ball.
And a few other ways but I really cannot remember! It's been a bit hectic.
So, I am asking, if anyone has any experience in this area could they please give me a push in the right direction? Im hoping to have the maze walls sorted by Tuesday however it's looking grim!
If you need any more information, please ask.
Thank you in advance for any and all replies.
Instead of having an ArrayList that you have to iterate over, why not store the maze the same way you do the text file? Use a 2D boolean array filled with true for wall and false for floor, or vice versa.
This simplifies finding a wall considerably. All you have to do is figure out where in your grid the ball is. Then you can just check the cells immediately surrounding it. Even if you include diagonals(which probably isn't necessary for an all-90-degree maze), this equates to checking 8 booleans from an array, basically instant.
As for the axis issue, just stop movement in that direction. No need to freeze a whole axis. For instance, if the wall is right of you, just don't allow x to go higher. No reason to not let it lower unless there's a wall to the left.
This is just a general idea, though. Since it's homework, no code for you ;)
Edit:
The 2D array is just that, a boolean[][] which holds true in each of the spots where you want a wall to be. When you read in your text file, just assign it straight away.
Assuming each line in your text corresponds to an y row, and each 0/1 is the x for that column, when you read a 1, assign map[x][y] = true.
I'm honestly not sure what else you need elaboration on. It's a common format to do simple tile-based maps, though. If you google "2d array tile map", you'll find several resources to help with it.

collision & touch + shoot methods for Android

I really need help. I am making a game app for my final year project. It is a simple game where you have to shoot a ball into a target by rebounding of walls or angled blocks. However i need help in 2 areas:
the shooting mechanism is similar to that of stupid zombies. There is a crosshairs where you touch on the screen to indicate which direction you want the ball to be shot at. On release the ball should move into that direction and hopefully gets into the target and if not gravity and friction causes it to come to a stop.
The problem is how do I code something like this?
I need the ball to rebound of the walls and I will have some blocks angled so that the ball has to hit a certain part to get to the target. The ball will eventually come to a stop if the target is not reached.
How can I make a method to create the collisions of the wall and blocks?
I have spent the last weeks trying to find tutorials to help me make the game but have not found much specific to the type of game I am making. It would be great if sample code or template could be provided as this is my first android app and it is for my final year project and i do not have much time left.
Thank you in advance
akkki
Your question is too generic for stack overflow no one is going to do your project for you. Assuming you have basic programming experience if not get books and learn that first.
Assuming you already chose Android because of your tag, and assuming 2d game as it is easier.
Pre requests:
Install java+eclipse+android sdk if you havent already.
Create a new project and use the lunar landar example, make sure it runs on your phone or emulator.
Starting sample:
The lunar landar has a game loop a seperate thread which constantly redraws the whole screen, it does this by constantly calling the doDraw function. You are then supposed to use the canvas to draw lines, circles, boxes, colours and bitmaps to resemble your game. (canvas.draw....) Lunar landar does not use openGL so its slower but much easier to use.
Stripping the sample:
You probably don't want keyevents or the lunar spaceship!
Delete everything in the onDraw function
Delete the onKeyUp, onKeyDown
Delete any errors what happen
Create a new
#Override
public boolean onTouchEvent(MotionEvent event){
return false;
}
Run it you should get a blank screen, this is your canvas to start making your game... You mentioned balls, break it down to what a ball is: A position and direction, create variables for the balls x,y direction_x and direction_y the touch event will want to change the balls direction, the draw event will want to move the ball (adding the direction x,y to the ball x,y) and draw the ball (canvas.drawCircle(x,y,radius,new Paint())) want more balls search and read about arrays. Most importantly start simple and experiment.
2 collisions
Collisions can be done in the dodraw function and broken down to: moving an object, checking if that object has passed where it is supposed to go and if so move it back before anyone notices.... There are many differently techniques of collision detection:
If your walls are all horizontal and vertical (easiest) then box collisions checks the balls new x,y+-radius against a walls x,y,width and height its one big if statement and google has billions of examples.
If your walls are angled then your need line collision detection, you basically have a line (vector) of where your ball is heading a vector of your wall create a function to check where two lines collide and check if that point is both on the wall and within the radius of your ball (google line intersection functions)
or you can use colour picking, you draw the scene knowing all your walls are red for example, then check if the dot where the new ball x,y is, is red and know you hit
Good luck, hope this helped a little, keep it simple and trial and error hopefully this gets you started and your next questions can be more specific.

Categories

Resources