I'm building a simulator that is based on car collisions on the road. The "cars" are basic rectangles drawn using fillRect and setting random x and y coordinates for each car. The kinematics portion of the simulator work perfect except when cars collide. What I'm trying to do is figure out a way to detect collision without re-inventing the wheel. In essence, is there such implementation in Java that helps with this type of situation?
If not, I have an idea that consists of putting every single x and y point in the area of the square into an array for each car. Then if the other car's "area" overlaps a coordinate with the other, then a collision would occur. Could this be a solution, or is there a simpler way of doing this? Perhaps some advice would be great!
If not, I have an idea that consists of putting every single x and y
point in the area of the square into an array for each car.
No need to reinvent the wheel. Are you using Rectangle objects for your cars underneath? You can call methods such as contains and intersects which are part of the Rectangle api to achieve what you want. You need to make sure you check the next movement of the Rectangles, looking for collisions, before you move them.
Look here.
Related
My question is mostly related to the theory behind it. I make a 2D game for a project and i detect collisions by using the .overlaps method in the Rectangle class and the collisions are handled beautifully. First of all , is that considered to be a continuous or discrete collision technique. As i'm reading the theory i say it is discrete ,however i'm reading in online articles that the major disadvantage of discrete is that it detects collision after it actually happened. So,my question is the following : is it actually discrete and if it is why i see no disadvantages?
Thanks
This is discreet because we only know if two bounding boxes collided after we check if the imaginary/invisible boxes intersected meaning they already overlapped. So by the time you take action (update) due to that collision, the objects are not in the collided position. Worse case, if they are not in relative speed, they can pass through. Think of the classic helicopter game where you dodge obstacles by going up and down. Say you put the velocity of the chopper on x really high, depending on your frame rate which depends on the hardware, you will see different positions of actual collision. For continuous, one object has to be aware of the physics properties of the other objects it may collide with to predict possible collision.
In reality, for 2d games like the helicopter game I mentioned, it really doesn't matter much. You can simulate the result of the collision by doing changes on an object's rotation, velocity, gravity and through some nice animations. If your game objects have abstract shapes, you should use something like box2d. There's a good Intersector class as well.
Also, you can experiment with different bounding box sizes (bounds) of an object rather than creating the bounding box of the object equal to its width and height.
I currently have an arraylist of points from a freehand drawing on a canvas. I was wondering if there is a simple algorithm to detect if that shape represents a circle.I have already researched this a little and the main items I am pointed at are either the Hough transform or having bitmap images but both of these seem a little over the top for what I need it for. Any pointers to algorithms or implementation would be very helpful.
thanks in advance sansoms,
If I interpret your question correctly, you want to know if all the points are on a circle.
As illustrated in the picture, we pick three points A, B, C from the list and compute the origin O of the presumed circle. By checking the distance between O and each point from the list, we can conclude whether these points are on a circle.
If you do not know what the user wanted to draw (e.g., a circle, an ellipse, a line, or a rectangle), you could use some basic optimization algorithm to find the shape best matching the hand-drawn points.
for each basic shape (oval, rectangle, triangle, line, etc.), create a random instance of that shape and measure the error w.r.t. the given points
optimize each of the shapes (individually) until you have the oval best matching the given points, the rectangle best matching the points, the best triangle, etc.
pick the shape that has the lowest error and draw it
Maybe this answer can give you some ideas: https://stackoverflow.com/a/940041/12860
In short: calculate the second derivative. If it is quite constand, it is probably a circle.
Reading your comment, an easier method to draw a circle is for the user to click the center point, then drag the radius of the circle. It's a lot less calculation, and easier for the user to draw.
You can do the same thing with a rectangle, or any other convex polygon.
For starters, how can I use defineCollisionRectangle API?
I've done some research about it and I think it doesn't have any use at all.
True that I can just use collidesWith() to check if 2 sprites collide.
But what I want to use a sprite that has parameters like house with a backyard fence around it.
I tried using the defineCollisionRectangle() in a condition, set it in the constructor but I don't know how to use it.
I can just use object.getX/gety and object.getWidth/getHeight, to make a Parameter around the sprite.
What does defineCollisionRectangle really do and how do I use it?
To detect collision for objects like house with a fence around it I would start with defining two Sprite objects - one for fence, another for house - each with its own collision rectangle.
To render a house with fence around it, I'd draw houseSprite over fenceSprite like at the sketch below:
With this approach it would be really easy to tell whether collision happened with fence or with house - simply because each defines its own collision rectangle.
Generally, when you find out that single collision rectangle doesn't do what you need, you invent a way to decompose things to more rectangular sub-elements so that when combined, these elements simulate / approximate desired behavior.
End users just don't care how many Sprite objects are there behind the scene. They're happy as long as end result feels about like house with a backyard fence around it.
I'm programming a Bomberman in Java following a tutorial (this is my first game).
The tutorial suggests the following code for detecting collisions.
for (int p=0; p<entities.size(); p++) {
for (int s=p+1; s<entities.size(); s++) {
Entity me = (Entity) entities.get(p);
Entity him = (Entity) entities.get(s);
if (me.collidesWith(him)) {
me.collidedWith(him);
him.collidedWith(me);
}
}
By now, entities is an array list containing the enemies and the player.
As I want to also detect the player collides with walls, should I put every single wall or bricks tile in the level into the entities arraylist? If so, isn't this algorithm very inefficient? These tiles aren't going to collide with other tiles, so I was thinking to manage game entities in different lists. What do you suggest? Is there a more efficient algorithm to do it?
Note: I already read other questions related to collisions in 2D games.
Thanks a lot.
I suggest reading this excellent article about how ghost movement and collision detection works in PacMan.
Then I would suggest logically modeling your Bomberman levels as a collection of tiles. Each tile represents a discrete position in your level, and it is not logically possible to ever be "between" tiles or occupying two tiles at the same time. Each tile can track what sort of terrain feature is currently on it, and whether or not it is a valid destination tile for the player (and the enemies, potentially with different rules for each if the enemies are allowed to traverse terrain that is normally impassable for the player).
Then you don't need a collision detection algorithm for every object in the world. When it comes time for an enemy to move, or when the user tries to move their character, all you have to do is check all the tiles that are adjacent to their current tile (4, or 8 max if you allow diagonal movement), see if each tile represents a valid movement direction, and block the movement if it is not in a valid direction.
And to answer your question, yes, iterating every object in the world on every position update will be very inefficient.
There is another way to use grids for collision system. I'm using more complex version of the Aroth's suggestion and using this to fix collision bugs.
Theoretically this system is the fastest(assuming you are doing this check if(Grid[x][y] ==true)) because it only uses a single Boolean check for each entity(the things that can move).
Note: In the above grid check example, I've used a 2 dimensional array of booleans that sets the coordinates of impassable grids to false.`
If you are not worried about physics like bouncing from a wall you can use this:
1- Divide the map into grids.
2- Making every entity only fill a tile would be better but not necessary.
3- Store the previous position or the grid of the entities.
4- Whenever an entity moves, before visually updating their location (also before
doing other calculations) check the grids they are in. If they are in grid
that is not empty or simply in a grid that they are not supposed to
be, return their position back to the previous position (which you have stored).
If you want to allow entities to move freely inside the grids(the grids are bigger than the minimum distance they can move) then you need to put them adjacent to the grids they've entered and they weren't supposed to. Otherwise just return them back to the previous grid.
If you want them to bounce from the wall you can still use this but I'm not sure how many features can be added to a collision system like this.
May I recommend my own project. But it's still wip.
https://github.com/YagaoDirac/Dirac-2d-collision-detection-for-games
It's based on quad-tree which handles sparse pretty well.
It supplies collision group. This conception is also used in both UE and Unity.
It support only circle vs circle and overlapping only for now(2022 feb 22).
I plan to make at least AABB, and collision which at least stop your pawn from leaving the map.
I may also provide another system based on fixed grid.
I'm currently writing an application that actually acts as a "cut" tool for 3D meshes. Well, I had some problems with it now which I am clueless on how to solve, since it is my first application.
I have loaded a model from an object file onto the canvas, then on the same canvas, I use the mouse drag event to draw lines to define the cutting point.
Let us say I want to cut a ball into half and I draw the line in the middle. How do I detect the vertices of the ball under the line.
Secondly, if I rotate/translate the ball, would all the the vertices information change?
Think of what you'd do in the real world: You can't cut a ball with a line, you must use a knife (a line has no volume). To cut the ball, you must move the knife through the ball.
So what you're looking after is a plane, not a line. To get such a plane, you must use some 3D math. What you have is the canvas orientation and the "side view" of the plane (which looks like a line).
So the plane you're looking for is perpendicular to the canvas. A simple way to get such a plane is to take the canvas orientation and create a plane which has the same orientation and then rotate the plane around the line by 90°.
After that, you can visit all edges of your model and determine on which side of the plane they are. For this, determine on which side of the plane the end points of the edge are. Use the cross product. If they are on the same side (both results of the cross products will have the same sign), you can ignore the edge. Otherwise, you need to determine the intersection point of the edge and plane. Create new edges and connect them accordingly.
See this page for some background on the math. But you should find some helper methods for all this in your opengl library.
if I rotate / translate the ball, would all the the vertices information change
Of course.
It's not going to be that easy.
I assume the line you are drawing induces a plane which then cuts the sphere.
To do so, you have to calculate the intersecting area of the sphere and the plane.
This is not a trivial task and I suggest using an existing framework for this or if you really want to do this yourself, read about basic intersection problems to get a feeling for this kind of problem. This paper offers a good introduction to various intersection tests.
In general boundary represended volumes, as in your case, are difficult to handle when it comes to more advanced manipulations. Cutting a sphere in half is easy compared to burring a small hole into it. Sometimes it's better to use a volume representation, like tetrahedral meshes or CSG.
Regarding your second question, you shouldn't rotate or translate the sphere, rotate and translate the camera.