How to tell the direction of the given points [closed] - google-maps

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I am coming up or am looking for an equation to this trivial problem:
Well it's more about knowing the direction in which the user is going based on the users geo location.
As you can see below the User's first coordinates are in point x after a minute or two the user's coordinates changed and is now at point y
Given the User's coordinates x and y , the Intersection point A and Point B
how do I come up with a formula that would tell me if the user is in the right lane (going from point B to point A)
or is in the left lane (going from point A to point B).

Assuming this is just coordinate based, and does NOT need to take into consideration the road or path the points are on, use the dot product. Create segments from points and dot product of two segments is positive if segments are aligned (point is same direction with less than 90 degrees) and negative if segments point in opposite directions.
If problem needs to consider the road or path, then the below will not work, because road/path may at times curve back and be moving away from destination, so correct direction on the road/path would temporarily be increasing distance to destination (as the crow flies). As your question is worded it SOUNDS like you want to be able to tell, from a single user position X and Y values which lane of a defined road they are in. If you think about it, that is simply not possible without knowing the exact geometry of the road/path itself. If it is curved at all, it becomes impossible to determine. Think about it. For ANY given position on the ground, you could bend the road one way or the other to cause that spot to be in either lane...
But with TWO positions, that represent movement in time, and the assumption that they are moving forward in whatever lane they are in, you CAN determine whether that motion is more towards Point A or towards Point B.
Technically, dot product of two vectors A and B
A dot B = |A| x |B| x Cos(Angle between them))
So, and AGAIN, this is assuming you don't need to take into consideration the shape or curvature of the road, you just make two directed segments, one from B to A, and another from one user position to a subsequent user position (representing his/her motion during some finite time interval), and take the dot product of these two segments. If it's positive, he's moving towards A, if negative, hes moving towards B.
(this code is simplified)
public struct Point
{
public double X { get; set; }
public double Y { get; set; }
private Point(double xValue, double yValue)
{ X = xValue; Y = yValue; }
public static Point Make(double x, double y)
{ return new Point(x, y); }
}
public class Segment
{
public Point StartPoint { get; set; }
public Point EndPoint { get; set; }
#region ctor / factories
protected Segment(Point startPoint, Point endPoint)
: base(startPoint, (endPoint.Y - startPoint.Y) /
(endPoint.X - startPoint.X))
{
StartPoint = startPoint;
EndPoint = endPoint;
}
public static new Segment Make(Point startPoint, Point endPoint)
{
if (startPoint == endPoint)
throw new Exception(
"You must use two different points to define a segment.");
return new Segment(startPoint, endPoint);
}
public static new Segment Make(double ax, double ay, double px, double py)
{ return Make(Point.Make(ax, ay), Point.Make(px, py)); }
public static Segment NullSegment { get { return new Segment(); } }
#endregion ctor / factories
public double Length
{
get
{
return Math.Sqrt(
Math.Pow(EndPoint.Y - StartPoint.Y, 2) +
Math.Pow(EndPoint.X - StartPoint.X, 2));
}
}
public double DotProduct(Segment seg, bool normalize = false)
{
double
dAx = EndPoint.X - StartPoint.X,
dAy = EndPoint.Y - StartPoint.Y,
dBx = seg.EndPoint.X - seg.StartPoint.X,
dBy = seg.EndPoint.Y - seg.StartPoint.Y;
var dP = dAx * dBx + dAy * dBy;
return normalize? dP / Length / seg.Length : dP;
}
}

Related

Explanation to why two constructors are required

Unfortunately, I do not feel confident with my understanding of default constructors.
I have searched extensively to find a resource that provides an explanation to adhere to my personal learning curve of the Java language. However, upon completing an assignment, I feel I may not be meeting the assignment criteria due to my own feeling of redundancy to need for a default constructor. This is why i feel like i am misinterpreting the concept of different types of constructors all together.
I have created two constructors as the assignment requires. One that takes in no parameters and initializes instance variables to a default value. And another that takes in parameters to give values to the object variables when the new object is created in the main method.
Why am I creating a default constructor for the object if the default is never used in the main method? Below is a sample of my code:
public class Circle {
private double x; // declaring variable to hold value of x coordinate
private double y; // Variable to hold value of y coordinate
private double r; // Variable to hold value of the radius of a circle
/* default constructor */
Circle() {
x = 0.0;
y = 0.0;
r = 0.0;
}
/* constructor takes in three parameters and sets values for variables x, y, and r */
public Circle(double x, double y, double r) {
this.x = x;
this.y = y;
this.r = r;
}
// test class created for main method
public class TestCircle {
public static void main (String[] args){
Circle c1 = new Circle(2.0,3.0,9.0);
System.out.println();
System.out.println(" A circle object has been created with the following attributes:");
c1.printAttributes();
System.out.println();
System.out.println("The circle is tested for the maximum radius of 8.0...");
c1.setRadius(8.0);
System.out.println();
System.out.println("... since the radius is more than the allowable maximum, the new attributes for the Circle are:");
c1.printAttributes();
System.out.println();
System.out.println("The area of the Circle is " + c1.area());
System.out.println("The Circumference of the circle is " + c1.circumference());
System.out.println();
System.out.println("The origin of the circle is now moved by a specified amount...");
c1.move(6,-7);
System.out.println();
System.out.println("The new attributes of the circle are:");
c1.printAttributes();
System.out.println();
System.out.println("Testing if the point (10,-20) is inside the circle...");
System.out.println();
if (c1.isInside(10,-20)){
System.out.println("The point (10,-20) is inside the circle");
}
else {
System.out.println("The point (10,-20) is not inside the circle");
}
} // end of main
} // end of class
If you don’t use it you should delete it. Sometimes you will need to create empty objects in order to set attributes a posteriori, but if you are not using it at all there is no point to have it
The point of making default constructors is sometimes for back end stuff and is considered a "good programming practice" no you don't use the default constructor here in your main and in fact your code would run just fine with no default constructor comment it out and re run your tester you will see it works fine.

Pattern creation of collectibles - LibGdx

I am working on a LibGdx running game.I have collectibles/coins in the game.
I have created a coin array,and spawned it throughout the game.
To improve the play,I want to make patterns of coins.Like 2 coins or 3 coins together , coins in vertical or diagonal arrangements etc.
I tried to implement this,but found it a difficult task as a fresher.
Please suggest me some code to implement patterns like triangle with an array of objects.
Like this:triangle with 3 coins in equal distance:
My coin array and method are included here:
I am adding new coins on the basis of last coin passes a particular distance on the screen.
Array<Coin> coins = new Array<Coin>();
private void createCoin() {
coinObj = objectFactory.createCoin(CoinEnum.random());
coinObj.isCollided = false;
coins.add(coinObj);
}
private void spawnCoin() {
if (coins.size == 0) {
createCoin();
} else {
Coin c = coins.peek();
if (c.getY() > (Constants.WORLD_HEIGHT / 8))
createCoin();
}
// remove out of screen coins
if (coins.size > 0) {
Coin cc = coins.first();
if (cc.getY() > Constants.WORLD_HEIGHT) {
coins.removeValue(cc, true);
}
}
}
Also hope someone can tell me the mistakes in my approach if any!
Thanks in advance!
First of all, try to model the CoinPattern:
- What is a CoinPattern?
It is just a pattern, describing an arrangement of multiple coins.
- What do I need to describe it?
As it is just a pattern, you don't need no Coins yet.
In my opinion, a list of Points (or Vector2) should be enough.
Each of these Points could describe the relative Position of the Object (in your case Coin) inside the Pattern.
Now you could create constants for your Patterns. The triangle could look something like this:
public static final PATTERN_TRIANGLE = new Vector2[] {
new Vector2(0,0),
new Vector2(1,0),
new Vector2(0,1),
};
Then you could create a method spawnPattern(Vector2[] pattern, int x, int y). This method should then create a Coin for every Vector2 in the pattern.
The position of each Coin could be calculated like this:
int posX = x + pattern[i].x;
int posY = y + pattern[i].y;
Note, that using this methode, the positions of the Coins are relative to the lower, left corner of the Pattern position.

How I can calculate the endpoint of a line, if I have the starting point, the angle and length of the line?

Point 1, say it is (0, 0) and I have another point that should turn around at a distance of 10f. Then I'll adding degrees angle to make it rotate. I be wanting to know how to calculate that point that this turning around each other ..
I will use the raycasting, I need to rotate the ray (clockwise) to detect collisions
So you say you have point1 and point2, both separated by a distance of 10f where point2 will be rotating around point1, and you want to know if between this separation an object at some point is intersecting them, something like the following image:
There are tutorials to get the maths for rotate a point arount another one in internet, like this one, and since you can't specify an origin for a Vector2, a translated version of the code proposed in the previews link to java should be something similar to:
public Vector2 rotatePoint(Vector2 center, Vector2 point, float angle) {
angle = angle * MathUtils.degreesToRadians; // Convert to radians
float rotatedX = MathUtils.cos(angle) * (point.x - center.x)
- MathUtils.sin(angle) * (point.y - center.y) + center.x;
float rotatedY = MathUtils.sin(angle) * (point.x - center.x)
+ MathUtils.cos(angle) * (point.y - center.y) + center.y;
// rotated new position:
return new Vector2(rotatedX, rotatedY);
}
As for the rest of the code (the intersection between objects), I guess you are looking for the RayCastCallback interface:
// initial position
Vector2 point1 = new Vector(0, 0);
// Max lenght of view
Vector2 point2 = new Vector(0, 10);
// Position of collision if occur
final Vector2 collisionPoint = new Vector();
#Override
public void render(float delta) {
//...
point2 = rotatePoint(point1, point2, 10); // rotate 10º
// to detect if object at position point1 is seeing something
world.rayCast(new RayCastCallback(){
#Override
public float reportRayFixture(Fixture fixture, Vector2 point,
Vector2 normal, float fraction) {
// what do the object saw? -> fixture
// where do the object saw it? -> point
collisionPoint.set(point);
return 0; // <- return 0 to stop raycasting
}
}, point1, point2);
//... rotation and other stuffs...
}
The return parameter of reportRayFixture have this documentation:
Called for each fixture found in the query. You control how the ray cast proceeds by returning a float: return -1: ignore this fixture and continue return 0: terminate the ray cast return fraction: clip the ray to this point return 1: don't clip the ray and continue. The Vector2 instances passed to the callback will be reused for future calls so make a copy of them!
** Emphasis added.
Basically it says that you can check for all the intersections one by one, but if you care only for the first one, return 0 immediately. This is useful when you want to know if an object is being blocked by another one. In this case, I return 0 and copy the value of point to collisionPoint to let you do whatever you want to do with this value.
A very nice example can be found in this video.
Hope you find this useful.
You should consider using Intersector class to check if the line from your actor intersects with the body shape.
To calculate end of "sight" line use Vector2 that you will be rotating according to your actor rotation (which is actually answer for your question)
It should looks like:
Vector2 sightVector = new Vector2(10f, 0); //the 10f is actually your sight max distance
sightVector.rotate(actor.getRotation());
...
#Override
pblic void render(float delta) //it can be also act of the actor
{
sightVector.rotate(actor.getRotation());
Vector2 endOfLine = new Vector2(actor.getX() + sightVector.x, actor.getY() + sightVector.y); //here you are calculating the end of line
Polygon bodyShape = getBodyShape( theBody ); //you should create a method that will return your body shape
if( Intersector.intersectLinePolygon(new Vector2(actor.getX(), actor.getY()), endOfLine, bodyShape) )
{
//do something
}
...
}
Intersector has method to check intersection with circles etc also so your body Shape doesn't need to be polygon

LibGdx Bow and arrow game physics

I'm working on a new game written with LibGdx Engine and Java.
I've got a problem with some of the physics in this game.
I want to shoot the arrow in a ballistic trajectory (angry bird style)
and can't find the equation to do so .
I am using these velocity equations:
float velx = (float) (Math.cos(rotation) * spd);
float vely = (float) (Math.sin(rotation) * spd);
I add this to the current position and the arrow shoots in one direction - straight.
I thought maybe changing the rotation would help me achieve what I want (a ballistic path).
It does help, but I want to have the trajectory as well.
I saw this
ProjectileEquation class that someone already posted but didn't know how to work with it:
public class ProjectileEquation
{
public float gravity;
public Vector2 startVelocity = new Vector2();
public Vector2 startPoint = new Vector2();
public Vector2 gravityVec = new Vector2(0,-10f);
public float getX(float n) {
return startVelocity.x * (n ) + startPoint.x;
}
public float getY(float n) {
float t = n;
return 0.5f * gravity * t * t + startVelocity.y * t + startPoint.y;
}
}
I'm looking for some help to help me use this class for ballistic trajectories.
This is how I tried using it:
for(int i =0;i<30;i++)
{
Texture f = ResData.Square_1;
ProjectileEquation e= new ProjectileEquation();
e.gravity = 1;
e.startPoint = new Vector2(bow.getX(),bow.getY());//new Vector2(-bow.getX(),-bow.getY()); //My bow is opposite so it suppose to work fine
e.startVelocity = getVelocityOf(bow.getRotation());
Vector3 touchpos = new Vector3();
s.draw(f,e.getX(i) ,e.getX(i),5,5);
}
The ProjectileEquation class you post looks like it'll calculate the X and Y position given a time delta, so the float you pass in should be the time delta since you started the arrow moving (in seconds).
That code will not give you the angle of the arrow though. To find that, I would suggest you keep hold of the previous X and Y, then you can use Math.atan2() to calculate the angle based on the previous XY and the current XY. Google atan2 for a load of info on how to use it.
The very best way to do this however would be to use Box2d and model the scene correctly. Then you wouldn't have to get involved in the maths at all. I read somewhere that that's what Angry Birds uses, and is an excellent choice for modelling these sorts of physics games.
I hope your game goes well.

How to draw paths specified in terms of straight and curved motion

I have information on paths I would like to draw. The information consists of a sequence of straight sections and curves. For straight sections, I have only the length. For curves, I have the radius, direction and angle. Basically, I have a turtle that can move straight or move in a circular arc from the current position (after which moving straight will be in a different direction).
I would like some way to draw these paths with the following conditions:
Minimal (preferably no) trigonometry.
Ability to center on a canvas and scale to fit any arbitrary size.
From what I can tell, GDI+ gives me number 2, Cairo gives me number 1, but neither one makes it particularly easy to get both. I'm open to suggestions of how to make GDI+ or Cairo (preferably pycairo) work, and I'm also open to any other library (preferably C# or Python).
I'm even open to abstract mathematical explanations of how this would be done that I can convert into code.
For 2D motion, the state is [x, y, a]. Where the angle a is relative to the positive x-axis. Assuming initial state of [0, 0, 0]. 2 routines are needed to update the state according to each type of motion. Each path yields a new state, so the coordinates can be used to configure the canvas accordingly. The routines should be something like:
//by the definition of the state
State followLine(State s, double d) {
State s = new State();
s.x = s0.x + d * cos(s0.a);
s.y = s0.y + d * sin(s0.a);
s.a = s0.a;
return s;
}
State followCircle(State s0, double radius, double arcAngle, boolean clockwise) {
State s1 = new State(s0);
//look at the end point on the arc
if(clockwise) {
s1.a = s0.a - arcAngle / 2;
} else {
s1.a = s0.a + arcAngle / 2;
}
//move to the end point of the arc
State s = followLine(s1, 2 * radius * sin(arcAngle/ 2));
//fix new angle
if(clockwise) {
s.a = s0.a - arcAngle;
} else {
s.a = s0.a + arcAngle;
}
return s;
}