Collision between a moving circle and a stationary circle - java

So what I'm trying to make is a function where I input the location of a moving circle and its target location, the location of a stationary circle and both of their radiuses, and I want to return the point at which they intersected if they did and the target location if they didn't.
The starting position of both circles, their radiuses and the end position of the moving circle are all known.
In this example I want to in a single frame move circle A from point Start to point End, if A collides with B I want to return the point where they touch closest to Start. In between Start and End there is a vector that can be calculated through End-Start which I'll call V and use in my attempt at solving this.
I will to refer the point Start as S and the position of B as P, the radius of A as Ra and the radius of B as Rb as seen in this image: variables.
So this is how far I've got:
When the two circles are just about touching the distance between them should be their radiuses combined like in this image: radiuses combined.
Therefore Ra+Rb = length of P-C which becomes (Ra+Rb)² = (P.x-C.x)² + (P.y-C.y)² according to Pythagoras (I squared both sides to remove the square root)
C can be described as the point S plus the vector V scaled by some constant t, C = S + tV so for example the point half way between Start and End could be described as S + 0.5V.
So the equation would then become (Ra+Rb)² = (P.x-(S.x+tV.x))² + (P.y-(S.y+tV.y))²
I have not gotten further than that since I cant isolate t which I need to find C
Any help is greatly appreciated! Sorry if I made any mistakes, its my first time posting.
(If anyone has code in Java for this that would be amazing)

You would probably have received a better answer for your question over at math.stackexchange.com, since this really seems to be a question about the maths related to your program.
But anyhow, this problem can be solved in a few steps:
1. Projection of a point onto a line:
Let Q be a projected point on V. Is the distance P-Q larger than the sum of Ra and Rb? If so, there is no collision, else proceed:
2. Pythagoras:
You now know the distance P-Q, and as you noted yourself, the circles will intersect at a distance Ra+Rb - if they collide. So, now if we find the distance Q-C, we can find where C is, since we already know where Q is from the projection onto V.
So, what is the distance Q-C: Sqrt((B-Q)^2 - (B-C)^2)
3. Find C by translating Q by distance Q-C
Now, you just need to make sure that you translate Q in the right direction: toward S.
As for the coding part of your problem, there was never a question asked, so there's nothing to respond to...
[Edit: fixed #3 Translate->Find]

Related

Sphere-Sphere Intersection, choosing right theta

I am working on a C++ problem where I'm trying to make a utility function that takes as input two line segments starting points in 3d space [(x,y,z) and radius r]. If the segments can be oriented such that they end at the same point, the function should return true and print out that point. If there are multiple orientations that would produce a common endpoint, the function should choose the one that is furthest in the direction indicated by hint_direction.
The function receives these values:
bool func(
point3d position_0, // origin of first line segment.
float length_0, // length of first line segment.
point3d position_1, // origin of second line segment.
float length_1, // length of second line segment.
vector3d hint_direction, // in the event there are multiple solutions, return the one furthest in this direction.
point3d *out_common_end_position) // if result is true, point where both line segments can be oriented to end. otherwise uninitialized.
I have been following some guides online which lay out how to do this such as this: https://gamedev.stackexchange.com/questions/75756/sphere-sphere-intersection-and-circle-sphere-intersection.
I was able to successfully get all the intersecting points, but I cannot figure out how to get a point that is furthest in the hint direction.
I thought I might be able to use the intersection point between circle and hint_direction and get a angle of that point, but I cannot figure out how to do so.
As Spektre correctly pointed out I missed the 3D portion of your question, so the 4 options are the following:
no intersection (or one sphere completely lies within the other)
a single point (spheres touch from inside or outside)
a normal intersection forming a circle
both spheres overlap completely, i.e. they have the same origin and the same radius
Since the normal intersection would form a circle you'd want to project the direction hint onto that circle and calculate the intersection between the circle and the projected vector to get the farthest intersection point.

Calculating normals of .3ds model

I'm trying to implement .3ds importer according to this documentation and I've approached the stage when I need to calculate vertex normals because .3ds files do not provide such. Here is the Java code:
/* Sctructure of vertex array is {x0, y0, z0, x1, y1, z1...}
*
* Basically, MathUtils.generateNormal_f(x0,y0,z0, x1,y1,z1, x2,y2,z2) is cross
* product between (x1-x0, y1-y0, z1-z0) and (x2-x0, y2-y0, z2-z0) */
normals = new float[this.vertex.length]; //every vertex has it's own normal
int n = 0;
for (int i=0; i<this.index.length; i++){
float[] Normal = MathUtils.generateNormal_f( //getting xyz coords of 1 normal
vertex[index[i]*3], vertex[index[i]*3+1], vertex[index[i]*3+2],
vertex[index[++i]*3], vertex[index[i]*3+1], vertex[index[i]*3+2],
vertex[index[++i]*3], vertex[index[i]*3+1], vertex[index[i]*3+2]);
normals[n++] = Normal[0];
normals[n++] = Normal[1];
normals[n++] = Normal[2];
}
Method MathUtils.generateNormal_f(...) tested and works fine. Result of this code can be seen below (first image). Just for example, in the second image, every normal of the model is the same and pointing towards the source of light.
Question is: how to calculate normals properly?
Your normals might be inverted.
I do not remember the 3ds format very well, but check if you can export and import the normals from the file instead of calculating them.
P.S. also do not use magic like this:
vertex[index[i]*3], vertex[index[i]*3+1], vertex[index[i]*3+2],
vertex[index[++i]*3], vertex[index[i]*3+1], vertex[index[i]*3+2],
vertex[index[++i]*3], vertex[index[i]*3+1], vertex[index[i]*3+2]
You will get different results based on the sequence of argument evaluation. better explicitly use [i], [i+1], [i+2] when calling calculate normal...
This information is correct as far as I know, and it's worked for me. For any 3 points A, B, and C on a plane, the normal, if we start at A, then B, and finally C, will be:
Where (B - A) and (C - B) each subtract two vectors, and the X sign represents finding the cross product of two vectors. The order of the points is quite important and determines our normal direction. If A, B, and C are organized in a counter-clockwise direction, than their normal will face outside the solid. If you want to know what a cross product is, then for any point P and Q, their cross product would be:
Another thing that is often done to the normal vector is that it is normalized. What this does is make the magnitude of the normal vector equal to 1 so that it is easier to work with. here's the equation:
Where the dot represents a dot product. If you don't know what a dot product is, allow me to illustrate by the following. For any points P and Q, their dot product, which is a scalar value, is:
Now that you have the surface normals, you can properly calculate the vertex normals for each vertex by averaging out the normals of any surface which shares that vertex. I don't have that formula on me, but I do know there are two approaches to find the vertex normal: weighted and non-weighted. A weighted approach involves calculating the area of each surface, while a non-weighted approach does not.
Hopefully, this information will help you. I leave the rest up to you or anyone else, as the remaining information is beyond my realm. Perhaps I'll come back and research some more on this question.

Closest Point on a Map

I am making a program where you can click on a map to see a "close-up view" of the area around it, such as on Google Maps.
When a user clicks on the map, it gets the X and Y coordinate of where they clicked.
Let's assume that I have an array of booleans of where these close-up view pictures are:
public static boolean[][] view_set=new boolean[Map.width][Map.height];
//The array of where pictures are. The map has a width of 3313, and a height of 3329.
The program searches through a folder, where images are named to where the X and Y coordinate of where it was taken on the map. The folder contains the following images (and more, but I'll only list five):
2377,1881.jpg, 2384,1980.jpg, 2389,1923.jpg, 2425,1860.jpg, 2475,1900.jpg
This means that:
view_set[2377][1881]=true;
view_set[2384][1980]=true;
view_set[2389][1923]=true;
view_set[2425][1860]=true;
view_set[2475][1900]=true;
If a user clicks at the X and Y of, for example, 2377,1882, then I need the program to figure out which image is closest (the answer in this case would be 2377,1881).
Any help would be appreciated,
Thanks.
Your boolean[][] is not a good datastructure for this problem, at least if it is not really dense (e.g. normally a point with close-up view is available in the surrounding 3×3 or maybe 5×5 square).
You want a 2-D-map with nearest-neighbor search. A useful data structure for this goal is the QuadTree. This is a tree of degree 4, used to represent spatial data. (I'm describing here the "Region QuadTree with point data".)
Basically, it divides a rectangle in four about equal size rectangles, and subdivides each of the rectangles further if there is more than one point in it.
So a node in your tree is one of these:
a empty leaf node (corresponding to a rectangle without points in it)
a leaf node containing exactly one point (corresponding to a rectangle with one point in it)
a inner node with four child nodes (corresponding to a rectangle with more than one point in it)
(In implementations, we can replace empty leaf nodes with a null-pointer in its parent.)
To find a point (or "the node a point would be in"), we start at the root node, look if our point is north/south/east/west of the dividing point, and go to the corresponding child node. We continue this until we arrive at some leaf node.
For adding a new point, we either wind up with an empty node - then we can put the new point here. If we end up at a node with already a point in it, create four child nodes (by splitting the rectangle) and add both points to the appropriate child node. (This might be the same, then repeat recursively.)
For the nearest-neighbor search, we will either wind up with an empty node - then we back up one level, and look at the other child nodes of this parent (comparing each distance). If we reach a child node with one point in it, we measure the distance of our search point to this point. If it is smaller than the distance to the edges or the node, we are done. Otherwise we will have to look at the points in the neighboring nodes, too, and compare the results here, taking the minimum. (We will have to look at at most four points, I think.)
For removal, after finding a point, we make its node empty. If the parent node now contains only one point, we replace it by a one-point leaf node.
The search and adding/removing are in O(depth) time complexity, where the maximum depth is limited by log((map length+width)/minimal distance of two points in your structure), and average depth is depending on the distribution of the points (e.g. the average distance to the next point), more or less.
Space needed is depending on number of points and average depth of the tree.
There are some variants of this data structure (for example splitting a node only when there are more than X points in it, or splitting not necessarily in the middle), to optimize the space usage and avoid too large depths of the tree.
Given the location the user clicked, you could search for the nearest image using a Dijkstra search.
Basically you start searching in increasingly larger rectangles around the clicked location for images. Of course you only have to search the boundaries of these rectangles, since you've already searched the body. This algorithm should stop as soon as an image is found.
Pseudo code:
int size = 0
Point result = default
while(result == default)
result = searchRectangleBoundary(size++, pointClicked)
function Point searchRectangleBoundary(int size, Point centre)
{
point p = {centre.X - size, centre.Y - size}
for i in 0 to and including size
{
if(view_set[p.X + i][p.Y]) return { p.X + i, p.Y}
if(view_set[p.X][p.Y + i]) return { p.X, p.Y + i}
if(view_set[p.X + i][p.Y + size]) return { p.X + i, p.Y + size}
if(view_set[p.X + size][p.Y + i]) return { p.X + size, p.Y + i}
}
return default
}
Do note that I've left out range checking for brevity.
There is a slight problem, but depending on the application, it might not be a problem. It doesn't use euclidian distances, but the manhattan metric. So it doesn't necessarily find the closest image, but an image at most the square root of 2 times as far.
Based on
your comment that states you have 350-500 points of interest,
your question that states you have a map width of 3313, and a height of 3329
my calculator which tells me that that represents ~11 million boolean values
...you're going about this the wrong way. #JBSnorro's answer is quite an elegant way of finding the needle (350 points) in the haystack (11 million points), but really, why create the haystack in the first place?
As per my comment on your question, why not just use a Pair<Integer,Integer> class to represent co-ordinates, store them in a set, and scan them? It's simpler, quicker, less memory consuming, and is way more scalable for larger maps (assuming the points of interest are sparse... which it seems is a sensible assumption given that they're points of interest).
..trust me, computing the Euclidean distance ~425 times beats wandering around an 11 million value boolean[][] looking for the 1 value in 25,950 that's of interest (esp. in a worst case analysis).
If you're really not thrilled with the idea of scanning ~425 values each time, then (i) you're more OCD than me (:P); (ii) you should check out nearest neighbour search algorithms.
I do not know if you are asking for this. If the user point is P1 {x1, y1} and you want to calculate its distance to P2 {x2,y2}, the distance is calculated using Pythagoras'Theorem
distance^2 = (x2-x1)^2 + (y2-y1)^2
If you only want to know the closest, you can avoid calculating the square root (the smaller the distance, the smaller the square too so it serves you the same).

2D waypoint pathfinding: combinations of WPs to go from curLocation to targetLocation

Please take a moment to understand my situation. If it is not comprehendable, please tell me in a comment.
I have an ArrayList of Waypoints. These waypoints are not in any order. A waypoint has the following properties:
{int type, float z, float y, float x, float rotation}
This applies to a 3 dimensional world, but since my pathfinding should not care about height (and thus treat the world as a 2 dimensional one), the y value is ignored. Rotation is not of importance for this question.
In this 2 dimensional world, the x represents the x axis and the z represents the y axis.
If x increases, the object in the world moves east. If x decreases, the object in the world moves west.
If z increases, the object in the world moves north. If z decreases, the object in the world moves south.
Thus, these "new" waypoints can be simplified to: waypoint = {float x, float y}.
Now, these waypoints represent the X-axis (x) and Y-axis (z) locations of an object. Moreover, there is a current location: curLocation = {float x, float y} and a target location: tarLocation = {float x, float y}.
This is what I want to get:
All combinations of waypoints (aka: paths or routes) that will lead from curLocation to tarLocation under the following strict conditions:
The distance inbetween each waypoint may not be bigger than (float) maxInbetweenDistance. This includes the initial distance from curLocation to the first waypoint and the distance from the last waypoint to tarLocation. If no such combination of waypoints is possible, null should be returned.
When multiple waypoints are found within maxInbetweenDistance from a waypoint that lead towards the target waypoint, the closest waypoint should be chosen (even better would be if an alternative waypoint that is slightly further away would result in a new path with a longer distance that is also returned).
The order of returned waypoint combinations (paths) should be from shortest route (minimum distance) to longest route (maximum distance)
Finally, please consider these points:
This is the only thing I need to do AI/pathfinding wise, which is why I do not wish to use a full blown pathfinding or AI framework. I believe one function should be able to handle the above.
If returning all possible combinations of waypoints causes too much overhead, it'd also be fine if one can specify a maximum amount of combinations (but still ordered from closest to furthest). Eg. the 5 closest paths.
How would I achieve this? Any feedback is appreciated.
I think your solution is to start with Dijkstra's Algorithm to find the shortest path first. You can consider your waypoints to be a connected graph where nodes are connected if they are close enough in the xy plane then apply Dijkstra (there are many example code listings online).
Now you have the shortest path through your graph from start to finish, which will be composed of N edges of the graph.
You would next need to create N new graphs, each just like the first, but with one segment of your shortest route un-connected. Find the shortest routes from start to finish on these modified graphs. Now you have N+1 routes which you can sort by length.
Repeat this until you have found enough paths for your needs, or there are no unranked paths left.
I haven't found a name for this technique, but it is described as a modification to Dijkstra here.
If your waypoints possess connectivity, you should take a look at Dijkstra's shortest path algorithm. The first couple of google hits even lists an implementation in Java. (I can't tell if connectivity is known from the post, but it does contain the "graph-algorithm" tag, so I'll assume so). As the name suggests, this method give you a shortest path between the two nodes.
Your constraints are challenging, as is the need for all possible combinations of paths under those constraints. Again - assuming connectivity exists - your node adjacency matrix can enforce your maxInbetweenDistance rule. Likewise, you can use this matrix in obtaining the "next best" solutions. Once the optimal path is known, you can mark that path (or elements of it) as unavailable, then re-run Dijkstra's algorithm. By repeating this process, you can obtain a set of increasingly sub-optimal paths.
As a matter of convention: in most computational geometry problems, Z is the height, and the horizontal plane is formed by the XY axes.
Well the easiest to implement would probably be creating an ArrayList of paths, which would be in turn an ArrayList of waypoints, that contains ALL possible paths, then using a recursive function to return whether each path is Valid or not given the starting and finishing point values, and the max distance, and if a path is not valid remove it from the list. The next step would be going through each of the paths that is left and ordering them from shortest total distance to shortest. This would be the brute force method of getting what you want, so the least efficient one possible. When I get home tonight I will repost if some one already hasn't with a more efficient method for doing this in java.
Edit: if the brute force method is too much, the list of waypoints will have to be sorted some how, the best way is probably to sort them initially based on distance from the starting point.

Loop inside oval in Java

I need to examine each pixel inside an oval with Java.
For drawing, I am currently using:
drawOval(x,y,r*2,R*2).
However, since I need to get each pixel inside the Oval, I would like to create a loop that iterates inside it (assuming I have x,y,r and R). Is there any built in functionality for this purpose?
Thanks,
Joel
Java's Ellipse2D implements the Shape interface, so you can use one of the latter's contains() methods as required. It's also possible to render the Shape into a BufferedImage and traverse its WritableRaster.
simple canonical implicit equation for Oval is (with center 0; 0)
So yo can iterate throw all possible coordinates and check it using this equation.
I don't think there's any built in functionality for this.
Let's go through this step by step.
Assuming that your ellipse's center is at (0,0), one radius is a, other is b, the canonical equation is
x^2/a^2+y^2/b^2=1
Multiplying both sides with a^2 and b^2, you get
x^2*b^2+y^2*a^2=a^2*b^2
Now, you must do a double for loop. a and b must be positive. Pseudocode:
for x = -a; x <= a; ++x:
for y = -b; y <= b; ++y:
if(x^2*b^2+y^2*a^2 <= a^2*b^2)
// you're in your ellipse, do as you please
Of course, this will work only if center is at (0,0), so if you want this algorithm to work, shift your points appropriately using translation. If you leave the center somewhere else, this algorithm will get messier.
Note: didn't test this. If somebody sees a mistake, please point it out.

Categories

Resources