Java Collision Detection Not Working - java

I have made threads in the past about similar questions but because of my lack of detail the answers have not really been related to what I needed so I am going to try explain my question in as much detail as I can and hopefully it will be easier for you to understand what I require.
I watched Bucky's slick game tutorials on youtube and made a 2D Java game, the game is basically a 2D player viewed from above (birds eye view) can move around a 2D map with user key input (up, down, left, right). The map the player moves around is very small so that meant boundaries had to be set so that the player could not walk off of the map, to give you a better idea of how this was done, here is the tutorial for setting up the voundries:
http://www.youtube.com/watch?v=FgGRHId8Fn8
The video will also show you exactly what the game is like.
The problem is, these boundaries only require one axis meaning that if the player is walking down you say something like "if player gets to the coordinate (number) on the X axis change the player movement to the opposite direction so that he can not go any further."
Now this creates a problem for me because this only requires one axis so it easy to set up and understand but if you look on the video, on the map there is a house and I want my player not to be able to walk over that also but this deals with 2 dimensions, I have looked at things like rectangle collisions and have seen things relating to them in the other posts but I get confused because I am new to Java and havent really done much with it at the moment apart from watching Bucky's tutorials.
My code at the moment for my game class has got the following methods: init, render and update. So to sum it up I really just want to set up a way of not letting my player walk through the house, I will mention also (I should have mentioned it in my other threads) as I am very new to Java, could you please take a step by step method of showing me how to set up the collisions, I mean even the basics of things like making the rectangle if required.
If my code is required please tell me and I will post it as soon as possible.
Thank you in advance.

You can set up the board as a 2x2 grid of a class that has has property such as 'isBlocked'. By default the edges of the board would have this property set to true to prevent the character from walking off the edge. When you add other obstacles such as a house or a wall the grid position(s) the object occupies would also have the property set to true. Then when moving a character you just check if the grid position the character moves to has the property set to false to see if it's an allowable move. This also makes it quite trivial to save the level data so you can just load them from disk later on.

Two possible options:
Extend Shape or Rectangle or the relevant Slick objects (they should exist IMO) and just check for intersect()
Look for (x1,y1) and (x2,y2) values such that it starts outside and ends up inside.
Assuming you have intersect() methods:
//Grab the previous position
prevPosX = movingobject.X;
prevPosY = movingobject.Y;
//Update the position
movingobject.update();
//Test for collision
if(movingobject.intersects(targetobj)) {
//If it collided, move it back
movingobject.X = prevPosX;
movingobject.Y = prevPosY;
//And reverse the direction
//(might want to do other stuff - e.g. just stop the object)
movingobject.speed *= -1; //Reverse the speed
}

in this case your update class should also add one more condition to look for the house. let say the cooridnates of house(assuming rectanglular house here for other shape just change x and y values) are (x1,y1)(x1,y2)(x2,y2)(x3,y1) you have to add a condition to make sure
x value is not between x1 and x2 and at the same time y value cannot between y1 and y2.

Related

libgdx how to detect collisions?

I have a Problem to detect collisions. I'm using TiledMap and created a virtual joystick, so that its possible to move in every direction not just left, right, top, bottom. The Point of View is directly 90 degrees from the top.
I don't know if that's the purpose of a TiledMap, but I thought the maps are easy to create. But now I 've got Problems with the collision detection. Since the map is not arranged like a chessboard, for example, I need to check the whole Sprite for collision. Can you please explain me to how that works?
Thank You
First of all I recommend you to checkout this question to clear up some things, and to get a basic Idea how collision detection works with TiledMaps.
Summarized: Using a TileEditor you can add different layers to your TiledMap. One of theese layers can be a object layer which can be used for collision. For how to create and access the layer please checkout the linked question.
For your example there are some central questions which needs to be cleared out first:
Which shape and size do the colliding objects have?
Can the objects move in between two tiles?
What should happen on collision?
Pokemon is a super easy example. The Player has the size of exactly one tile and can not move in between them. If there is a collision the player just can't move.
If that is what you want you can just add a check before moving any object: If the next tile isn't valid just don't move the object. For the collision check you can just adapt the example code from the first answer.
On the other end of the specturm you could have different shaped objects with differnt scales which have a dynamic velocity and should bounce of the objects on the TileMap. In that case it could be clever to use box2d for collision detection like in this answer.
So depending on your needs just try to adapt any of the answers I linked. Maybe just start with a super simple box collision try to extend your code.
use this method
void isCollition(Object x, Object y) {
Boolean collide = false;
if (x.getX() + x.getwidth() < y.getX() + y.getWidth() ||
x.getY() + x.getHeight() < y.getY() + y.getHeight() {
collide = true;
}
return collide;
}

LibGDX/Java - Trying to find the vector from one object to another

I want to add springs in my game that work like the ones in sonic - i.e. if you can't get over an obstacle you have to hit a spring which sends the main character flying towards another spring that gets him over that obstacle. I drew a little diagram below to demonstrate what I mean (yellow arrows represent the direction the player will go towards and the red - are the springs).
In my Spring class I have created a method:
//The detection area (blue rectangle in the diagram)
public Rectangle broadPhaseDetection() {
broadPhaseRectangle = new Rectangle(getxPos() - broadPhaseLength, getyPos(),
broadPhaseLength, broadPhaseLength);
return broadPhaseRectangle;
}
If the Player collides with a Spring, I check to see if there's ANOTHER Spring within the blue area and if there is - calculate the vector that takes you towards that spring and send the player in that direction.
This seems like a very simple concept which has probably been done loads of times before, but I couldn't find any good examples online for some reason. Does anybody know how I can get the vector I need?
Any insight is highly appreciated, thanks.
If the position vector of the spring you hit is Vector2 v1, and the position of the second spring is Vector2 v2, then you just need v2.sub(v1).
If you are only interested in the direction rather than the length of the vector, you might want to normalize by doing v2.sub(v1).nor() (this gives you a vector pointing the right way, but with length 1)
Just subtract the destination from the source to get the vector between them. The vector from PointA to PointB is: PointB - PointA. (And to subtract two vectors, just subtract their components.)
In Libgdx a Vector2 can be used to track these, and it supports overloaded sub methods.

Java More Resourceful Collision Detection

I am making a game in java which involves characters moving around a map and having some solid collision objects (i.e. buildings) placed around the map by reading certain data from a text file. There will be multiple maps where these objects' locations will change. My question is would painting a rectangle in a certain color that indicates collision behind such structures or would reading mouse coordinates and searching an array of these structures to see if that point lies on a building, thus denying the move or altering, be more resourceful and/or quicker. If painting a rectangle is the best, would leaving it behind the structure or deleting it after detecting for collision be better. Thanks for your time!
In my junior year in college I worked on a Collision detection system algorithm for the windows phone. It is hardly perfect but it was EXTREMELY efficient and can be adapted to a majority of games.
The way that it worked was pretty simple. There were two types of objects; Collidable objects (such as enemies or buildings) and Objects that you wish to check for collisions with these collidable objects.
I had this idea when I was going through a data structures class and we spoke about Linked Lists. I thought what if each link was a collidable object that you could stick your game objects that were already created in it. Then as the game objects moved around you would have a lightweight way of checking their locations for collisions. Thus my system was born.
All it really is, is a class that fires off either every game cycle or when ever you choose to check for collisions. You give it your players location, or bullet location or what ever object you want to see if it is colliding with something and it searches all of the collidable object locations and conducts test to see if they are overlapping.
The real efficiency of it comes into play when you add in a second element (Locations AND quadrant)
For Example if I break the phone screen up into for parts and I know which quadrant my player or bullet is in I can choose to only scan a list of collidable objects that are within that quadrant. Thus cutting your search algorithm to a fourth of its origonal size.
There are many different ways of detecting collisions. This was a simple example I used in my class to show how you could detect two circles colliding that were actually squares. As you can see simply by taking the center point coords of the circles and the radius's you can calculate the hypotenuse and determine where or if they are touching.
Good luck! if you have any questions feel free to ask!
The last reply in this posting may help you out. It is a simple maze. The structure of the maze is controlled by a data file which simply contains 0, 1 to indicate a path or a wall. You navigate through the maze using the arrow keys. When an arrow key is pressed the code checks to make sure the next square is not a wall.

Calculating a point in 3D space

I am trying to locate a point in 3D space relative to the origin (0,0,0). I have 3 values to calculate this point with: a rotation in degrees about both the x and y axis as well as a "view distance". Using these values, how can I locate a point in 3D space relative to the origin? I have tried using basic trigonometric functions, but the results seem to be random. The image below gives a visual as to what needs to be done.
'vd' being the "view distance"
'c' being a value holder
'(x,y,z)' being the coordinate I am trying to find
What I am trying to do is find the point a player is looking at a certain distance away (find a point in the direct line of sight of the player out a certain distance). Keep in mind, the rotations about the x and y axis are constantly changing, but the view distance remains the same. If anyone has any suggestions, methods of how to do this, or needs clarification, please comment/answer below.
I am doing this in LWJGL, and the code I am using is as follows:
float c = (float)(Math.cos(Math.toRadians(A00.rot.y)) * view_distance);
locate.y = (float)(Math.sin(Math.toRadians(rot.y)) * view_distance);
locate.x = (float)(Math.cos(Math.toRadians(rot.x)) * c);
locate.z = (float)(Math.sin(Math.toRadians(rot.x)) * c);
EDIT:
My issue is that this current setup does NOT work for some reason. The math seems legitimate to me, but I must have something wrong somewhere in the actual setup of the graph..
I suggest looking up quaternions. No need to fully understand how they work. You can find ready made classes for java available on the internet as well. Quaternions allow you to represent a rotation in 3D space.
What I would then do, is to start with a vector representing the direction pointing forwards from the origin, and apply the same rotation that the player currently has to it. Now it is pointing in the same direction as the player. Now if you take the player's current point, and the direction vector we now have a ray describing where the player is looking at.
I suggest this link for further information on quaternions. They may look complex but, as I said, you don't need to fully understand how and why they work to be able to use them. Just copy the formulae and learn how they are used. Once you figure out how to use them, they make 3d rotations really easy.
http://content.gpwiki.org/index.php/OpenGL:Tutorials:Using_Quaternions_to_represent_rotation

designing picture puzzle

I am planning to develop a jigsaw puzzle game.
Now I already have images and image pieces, so we don't need algorithm to cut the image in pieces.
On the UI side there would be two sections
First section contains the broken images in random order.
Second section contains the outline of the full image. User need to drag and drop the the cut images onto the outline image.
I am not sure how can the pieces be matched on the the outline image?
Any idea about the algorithm or the starting pointers?
Allow the user to drag each piece into the outline area. Allow the piece to be rotated in 90 degree increments.
Option 1:
If a piece is in the correct location in the overall puzzle, and at the correct angle, AND connected to another piece, then snap it into place with some user feedback. The outside edge of the puzzle can count for a connection to edge pieces.
Option 2:
A neighbor is an adjacent puzzle piece when the puzzle is assembled. When the puzzle pieces are mixed up, they still have the same neighbors. Each puzzle piece (except the edge pieces) has four neighbors.
If a piece is near one of its neighbors at the correct angle relative to that neighbor, then snap it to the other piece. Then allow the two (or more) pieces to be dragged around as a unit, as is done with a single piece. This would allow the user to assemble subsections of the puzzle in any area, much like is done with a physical jigsaw puzzle, and connect the subsections with one another.
You can check the piece being moved to its four neighbors to see if they are close enough to snap together. If a piece has its proper edge close enough to the proper edge of its neighbor, at the same angle, then they match.
There are several ways to check relative locations. One way would be to temporarily rotate the coordinates of the piece you are testing so it is upright, then rotate the coordinates of all its desired neighbors, also temporarily, to the same angle. (Use the same center of rotation for all the rotations.) Then you can easily test to see if they are close enough to match. If the user is dragging a subassembly, then you will need to check each unmatched edge in the subassembly.
Option 2 is more complex and more realistic. Option 1 can be further simplified by omitting the rotation of pieces and making every piece the proper angle initally.
For a regular shapes you can go with a matrix. I recommend this as the first approach. Dividing the puzzle is as simple as defining X,Y dimensions of the matrix. For each piece you have a series of four values then, one for each side, saying whether it is flat, pointing out, or pointing in. This will give you a very classic jigsaw puzzle setup.
How the pieces actually look becomes a strict GUI thing. Now, for the first draft I recommend getting it working with perfectly square pieces. Taking rectangular bits of an image should be easy to do in any GUI framework.
To go to shaped pieces you'll need a series of templates. These will become masks that you apply to the image. Each mask clips out a tiny portion of the image to produce your piece. You'll probably need to dynamically create the masks in order to fit them to the puzzle. At first start with simply triangular connections. Once you have that working you can do the math to get nice bulbous connector shapes. Look up "clip" and "mask" in your GUI framework.
If you wish to do irregular polygon shapes that don't follow a general matrix layout, then you need to do a lot more work. This is why I recommend getting the square first working as a good example. Now you'll need to delve into graph theory and partitioning. Pick up some books on 3D programming -- focusing on algorithms, as they do partitioning all the time. Though I wouldn't doubt if there is a book with this exact topic in it.
Have fun.
the data structure is simple I guess- each peace will point to it's neighbors and will hold the actual shape to display.
on the MMI (UI) of the app - what is your developing environment ?
If it's windows - I would go with c# and winforms or even better wpf.
if it's unix, you'll have to get someone else's advise, as I'm not an expert there.
1) How to break image into random polygons
It seems that you have figured out this part. (from : "Now I already have images and image pieces, so we don't need algorithm to cut the image in pieces.")
2) what kind of data structure can solve the problem
You can create a Class Piece like Scribble class in this example and your pieces would be array of objects of Piece class.
So, you will have two arrays,
(i) actual image pieces array
(ii) image piece outline array
So, whenever you drag and drop one piece on to the full outline of image, it will check whether the image piece object is intersecting more than 80% and ID (member variable of Piece object) of actual image piece and image piece outline matches, then you got the right piece at right place...
3) UI implementation
Check this out.
You could make an array of objects of the class "PuzzleTile"
Every such tile has an image and an integer
After every move, check if the integers are sorted correctly, means:
123
456
789
You could make a function for that which returns a bool.
Note: I'm currently developing under C#, that's why it's probably easiest to realize especially this concept under C#, although other platforms need none up to barely some modification to this.

Categories