What i want :
I am using Orientation Sensor to get Azmuth value (Angle). i am also taking starting point from user and draw a circle. Now i want to draw next pixel on the point where the user is heading considering that one step is equal to 30 pixels.
As user starts walking i want to draw circles of user current position on the image of floor plan inserted on screen. I can't use GPS for this solution due to certain reasons.
Here are steps i am performing :
Get current user direction in angles from Orientation sensor.
User will touch on screen to draw starting point on image.
As user starts walking it will draw points on the image relative to user's real world direction like i showed in above image. How can i certainly achieve this given only starting point(pixelX,pixelY) and start angle of user and current angle where he just faced.
What we have achieved so far :
We can draw straight lines on 4 angles i.e 0 , 90,180 and 270 by just adding and subtracting pixels to current pixels.
newAzimuth is current angle of user direction
if (newAzimuth >= 45 && newAzimuth <= 135) {
startX = startX + oneStepPixelsWidth;
mScreenRotationTextView.setText("You turned (Right)");
} else if (newAzimuth > 135 && newAzimuth <= 225) {
mScreenRotationTextVniew.setText("You turned (Back)");
startY = startY + oneStepPixelsHeight;
} else if (newAzimuth > 225 && newAzimuth <= 315) {
mScreenRotationTextView.setText("You turned (Left)");
startX = startX - oneStepPixelsWidth;
} else if (newAzimuth > 315 || newAzimuth < 45) {
mScreenRotationTextView.setText("You turned (Front)");
startY = startY - oneStepPixelsHeight;
}
Given that calculated angles are:
Here's the equations for that.
X=distance*cos(angle)
Y=distance*sin(angle)
In your case distance will always be 30 pixel
so (30Cos(Angle),30Sin(Angle)) will give you your location.
To adjust your calculated angle to work you can rotate them with those formulas;
adjustedX = x cos(angle) − y sin(angle)
adjustedY = y cos(angle) + x sin(angle)
By exemple if the angle calculated are like this:
Then you will need to;
Rotate 90 degree right or 270 degree left.
Translate.
Rotate 270 degree right or 90 degree left.
private Pair<Double, Double> getPositionOf(Pair<Double, Double> lastPosition, double angle, int distance, int angleAdjustment)
{
final Pair<Double, Double> rotatedLeftPosition = rotateLeft(lastPosition, 360 - angleAdjustment);
final Pair<Double, Double> translatedLocation = applyTranslationTo(rotatedLeftPosition, angle, distance);
return rotateLeft(translatedLocation, angleAdjustment);
}
private Pair<Double, Double> rotateLeft(Pair<Double, Double> position, double degreeAngle)
{
double x = position.first;
double y = position.second;
double adjustedX = (x * Math.cos(degreeAngle)) - (y * Math.sin(degreeAngle));
double adjustedY = (y * Math.cos(degreeAngle)) + (x * Math.sin(degreeAngle));
return new Pair<>(adjustedX, adjustedY);
}
#NotNull
private Pair<Double, Double> applyTranslationTo(final Pair<Double, Double> position, final double angle, final int distance)
{
double x = distance * Math.cos(angle);
double y = distance * Math.sin(angle);
return new Pair<>(position.first + x, position.second + y);
}
Where angleAdjustment will be 90
Okay. My problem is kinda mind-blowing. Let's say that I have a constructor which looks like this:
public Ball(Random r, float halfphonewidth, float halfphoneheight, float cx, float cy){
//te wartosci odpowiadaja za losowe polozenie i losowe wektory
x = (halfphonewidth-48)*0.1f;
y = (halfphoneheight-48)*0.1f;
vx = -0.2f + r.nextFloat();
vy = -0.2f + r.nextFloat();
Log.i("", "\n\n" + this.vx + " " +this.vy+"\n\n");
health = 3;
}
Now let's say that I have a step() method declared somewhere - it works. Step:
public void step(){
x += vx;
y += vy;
if(x<2f || x > 98f)
vx =- vx;
if(y<2f || y > 98f)
vy =- vy;
}
I have an onTouch event that listens and checks the 'click coords'. I catch them and pass to the constructor (float cx, float cy).
The first position of the ball is static - I set it permanently in the constructor and move by 48 pixels (cause of image size). It starts from the bottom-center and floats to the random direction + when it collides with a wall it reverses it's vx & vy.
So! I need to point the ball in a direction I click! :D
I tried by scaling screen w/h with coordinate system, tried with implementing Vector2D class (cause it's missing in the newest java I think) but im not that good with linear algebra, tried with trygonometry(even cyclometry) (but I may be blind).
Is there anyone that can point me a solution? Which is the best way and which should I try to implement?
You need to calculate the difference between the coordinates of the current position and the click position:
double xDiff = clickPoint.x - ball.x;
double yDiff = clickPoint.y - ball.y;
then you move the ball with a velocity proportional to that difference, in your case you have to set the vx and vy like:
vx = xDiff * n;
vy = yDiff * n;
where the bigger n is, the faster the ball will reach the target. You need to update the xDiff and yDiff variables as the ball move, so when the difference is 0 the movement will stop.
I know the startpoint (the middle of the screen) and the angle (in my example 20°). Now I want to know the position on the edge of the screen, like an invisible line is drawn from the center to the edge in the given angle. For better explanation, I included an image:
One way to do this is to calculate a point on a circle with a radius equal to or greater than the maximum diagonal, and then just clip it to the screen boundary.
Using Pythagoras' theorem, the length of the maximum diagonal will be
float d = Math.sqrt((width/2)*(width/2) + (height/2)*(height/2));
So you can calculate the point on the circle like this (angle is in radians clockwise from the top):
float x = Math.sin(angle) * d;
float y = -Math.cos(angle) * d;
Then you have to clip the vector from the origin to the point to each of the 4 sides, e.g for the right and left sides:
if(x > width/2)
{
float clipFraction = (width/2) / x; // amount to shorten the vector
x *= clipFraction;
y *= clipFraction;
}
else if(x < -width/2)
{
float clipFraction = (-width/2) / x; // amount to shorten the vector
x *= clipFraction;
y *= clipFraction;
}
Also do this for height/2 and -height/2. Then finally you can add width/2, height/2 to x and y to get the final position (with the center of the screen being width/2, height/2 not 0,0):
x += width/2
y += height/2
Since in the digital world a real collision almost never happens, we will always have a situation where the "colliding" circle overlaps the rectangle.
How to put back the circle in the situation where it collides perfectly with the rectangle without overlap?
Suppose that the rectangle is stopped (null velocity) and axis-aligned.
I would solve this problem with a posteriori approach (in two dimensions).
In short I have to solve this equation for t:
Where:
is a number that answers to the question: how many frames ago did the
collision happen perfectly?
is the radius of the circle.
is the center of the circle
is its velocity.
and are functions that return the x and y coordinates of
the point where the circle and the rectangle collide (when the circle is
at position, that is in the position in which perfectly collide with the rectangle).
Recently I solved a similar problem for collisions between circles, but now I don't know the law of the functions A and B.
After years of staring at this problem, and never coming up with a perfect solution, I've finally done it!
It's pretty much a straight forward algorithm, no need for looping and approximations.
This is how it works at a higher level:
Calculate intersection times with each side's plane IF the path from current point to future point crosses that plane.
Check each side's quadrant for single-side intersection, return the intersection.
Determine the corner that the circle is colliding with.
Solve the triangle between the current point, the corner, and the intersecting center (radius away from the corner).
Calculate time, normal, and intersection center.
And now to the gory details!
The input to the function is bounds (which has a left, top, right, bottom) and a current point (start) and a future point (end).
The output is a class called Intersection which has x, y, time, nx, and ny.
{x, y} is the center of the circle at intersection time.
time is a value from 0 to 1 where 0 is at start and 1 is at end
{nx, ny} is the normal, used for reflecting the velocity to determine the new velocity of the circle
We start off with caching variables we use often:
float L = bounds.left;
float T = bounds.top;
float R = bounds.right;
float B = bounds.bottom;
float dx = end.x - start.x;
float dy = end.y - start.y;
And calculating intersection times with each side's plane (if the vector between start and end pass over that plane):
float ltime = Float.MAX_VALUE;
float rtime = Float.MAX_VALUE;
float ttime = Float.MAX_VALUE;
float btime = Float.MAX_VALUE;
if (start.x - radius < L && end.x + radius > L) {
ltime = ((L - radius) - start.x) / dx;
}
if (start.x + radius > R && end.x - radius < R) {
rtime = (start.x - (R + radius)) / -dx;
}
if (start.y - radius < T && end.y + radius > T) {
ttime = ((T - radius) - start.y) / dy;
}
if (start.y + radius > B && end.y - radius < B) {
btime = (start.y - (B + radius)) / -dy;
}
Now we try to see if it's strictly a side intersection (and not corner). If the point of collision lies on the side then return the intersection:
if (ltime >= 0.0f && ltime <= 1.0f) {
float ly = dy * ltime + start.y;
if (ly >= T && ly <= B) {
return new Intersection( dx * ltime + start.x, ly, ltime, -1, 0 );
}
}
else if (rtime >= 0.0f && rtime <= 1.0f) {
float ry = dy * rtime + start.y;
if (ry >= T && ry <= B) {
return new Intersection( dx * rtime + start.x, ry, rtime, 1, 0 );
}
}
if (ttime >= 0.0f && ttime <= 1.0f) {
float tx = dx * ttime + start.x;
if (tx >= L && tx <= R) {
return new Intersection( tx, dy * ttime + start.y, ttime, 0, -1 );
}
}
else if (btime >= 0.0f && btime <= 1.0f) {
float bx = dx * btime + start.x;
if (bx >= L && bx <= R) {
return new Intersection( bx, dy * btime + start.y, btime, 0, 1 );
}
}
We've gotten this far so we know either there's no intersection, or it's collided with a corner. We need to determine the corner:
float cornerX = Float.MAX_VALUE;
float cornerY = Float.MAX_VALUE;
if (ltime != Float.MAX_VALUE) {
cornerX = L;
} else if (rtime != Float.MAX_VALUE) {
cornerX = R;
}
if (ttime != Float.MAX_VALUE) {
cornerY = T;
} else if (btime != Float.MAX_VALUE) {
cornerY = B;
}
// Account for the times where we don't pass over a side but we do hit it's corner
if (cornerX != Float.MAX_VALUE && cornerY == Float.MAX_VALUE) {
cornerY = (dy > 0.0f ? B : T);
}
if (cornerY != Float.MAX_VALUE && cornerX == Float.MAX_VALUE) {
cornerX = (dx > 0.0f ? R : L);
}
Now we have enough information to solve for the triangle. This uses the distance formula, finding the angle between two vectors, and the law of sines (twice):
double inverseRadius = 1.0 / radius;
double lineLength = Math.sqrt( dx * dx + dy * dy );
double cornerdx = cornerX - start.x;
double cornerdy = cornerY - start.y;
double cornerdist = Math.sqrt( cornerdx * cornerdx + cornerdy * cornerdy );
double innerAngle = Math.acos( (cornerdx * dx + cornerdy * dy) / (lineLength * cornerdist) );
double innerAngleSin = Math.sin( innerAngle );
double angle1Sin = innerAngleSin * cornerdist * inverseRadius;
// The angle is too large, there cannot be an intersection
if (Math.abs( angle1Sin ) > 1.0f) {
return null;
}
double angle1 = Math.PI - Math.asin( angle1Sin );
double angle2 = Math.PI - innerAngle - angle1;
double intersectionDistance = radius * Math.sin( angle2 ) / innerAngleSin;
Now that we solved for all sides and angles, we can determine time and everything else:
// Solve for time
float time = (float)(intersectionDistance / lineLength);
// If time is outside the boundaries, return null. This algorithm can
// return a negative time which indicates the previous intersection.
if (time > 1.0f || time < 0.0f) {
return null;
}
// Solve the intersection and normal
float ix = time * dx + start.x;
float iy = time * dy + start.y;
float nx = (float)((ix - cornerX) * inverseRadius);
float ny = (float)((iy - cornerY) * inverseRadius);
return new Intersection( ix, iy, time, nx, ny );
Woo! That was fun... this has plenty of room for improvements as far as efficiency goes. You could reorder the side intersection checking to escape as early as possible while making as few calculations as possible.
I was hoping there would be a way to do it without trigonometric functions, but I had to give in!
Here's an example of me calling it and using it to calculate the new position of the circle using the normal to reflect and the intersection time to calculate the magnitude of reflection:
Intersection inter = handleIntersection( bounds, start, end, radius );
if (inter != null)
{
// Project Future Position
float remainingTime = 1.0f - inter.time;
float dx = end.x - start.x;
float dy = end.y - start.y;
float dot = dx * inter.nx + dy * inter.ny;
float ndx = dx - 2 * dot * inter.nx;
float ndy = dy - 2 * dot * inter.ny;
float newx = inter.x + ndx * remainingTime;
float newy = inter.y + ndy * remainingTime;
// new circle position = {newx, newy}
}
And I've posted the full code on pastebin with a completely interactive example where you can plot the starting and ending points and it shows you the time and resulting bounce off of the rectangle.
If you want to get it running right away you'll have to download code from my blog, otherwise stick it in your own Java2D application.
EDIT:
I've modified the code in pastebin to also include the collision point, and also made some speed improvements.
EDIT:
You can modify this for a rotating rectangle by using that rectangle's angle to un-rotate the rectangle with the circle start and end points. You'll perform the intersection check and then rotate the resulting points and normals.
EDIT:
I modified the code on pastebin to exit early if the bounding volume of the path of the circle does not intersect with the rectangle.
Finding the moment of contact isn't too hard:
You need the position of the circle and rectangle at the timestep before the collision (B) and the timestep after (A). Calculate the distance from the center of the circle to the line of the rectangle it collides with at times A and B (ie, a common formula for a distance from a point to a line), and then the time of collision is:
tC = dt*(dB-R)/(dA+dB),
where tC is the time of collision, dt is the timestep, dB is the distance to line before the collision, dA is the distance after the collision, and R is the radius of the circle.
This assumes everything is locally linear, that is, that your timesteps are reasonably small, and so that the velocity, etc, don't change much in the timestep where you calculate the collision. This is, after all, the point of timesteps: in that with a small enough timestep, non-linear problems are locally linear. In the equation above I take advantage of that: dB-R is the distance from the circle to the line, and dA+dB is the total distance moved, so this question just equates the distance ratio to the time ratio assuming everything is approximately linear within the timestep. (Of course, at the moment of collision the linear approximation isn't its best, but to find the moment of collision, the question is whether it's linear within a timestep up to to moment of collision.)
It's a non-linear problem, right?
You take a time step and move the ball by its displacement calculated using velocity at the start of the step. If you find overlap, reduce the step size and recalculate til convergence.
Are you assuming that the balls and rectangles are both rigid, no deformation? Frictionless contact? How will you handle the motion of the ball after contact is made? Are you transforming to a coordinate system of the contact (normal + tangential), calculating, then transforming back?
It's not a trivial problem.
Maybe you should look into a physics engine, like Box2D, rather than coding it yourself.
I need to be able to move my player x and y pixels in the same direction as a point to a point. It's hard to explain, but this is what I am trying to do:
Angles 1 and 2 have to be the same. Point 1 stays the same at (100, 100), however point 2 constantly changes and so must the angles. I have tried this:
moveRectangle.setX(touchEvent.getX());
moveRectangle.setY(touchEvent.getY());
float theta = (float) Math.toDegrees(Math.atan2(touchEvent.getY() - 100,touchEvent.getY() - 100));
float velX = (float) (getSpeed() * Math.cos(theta));
float velY = (float) (getSpeed() * Math.sin(theta));
player.move(velX, velY);
The above code is constantly run when the user puts his finger on moveRectangle (Point 2) and moves it. But the above code does not work. The player just moves in one of two directions. player.move just adds velX and velY velocity. So how can I get the two angles and move the player in the right direction? Thanks.
Would it be easier to approach this problem using a cartesian approach (vectors) versus polar approach (angle and magnitude)? So, if the player is at point p0 and the "finger" is at point p1, then the direction the player should be moving v is given by the vector p1-p0. You can then scale the resulting vector v by the player's speed, and add the player's speed to his position. You can do this easily on a frame-by-frame basis.
Do you need just to know velocity on X and Y axis? You can do it without using trigonometry (just use Pythagorean theorem).
final float deltaX = touchEvent.getX() - player.x; // player.x is point1.x
final float deltaY = touchEvent.getY() - player.y; // player.y is point1.y
final float length = Maths.sqrt((deltaX)^2 + (deltaY)^2);
final float itterations = length / getSpeed();
final float velX = deltaX / itterations;
final float velY = deltaY / itterations;
player.move(velX, velY);
Or you need a code of player moving in cycle?
Remove Math.toDegrees().
From the Math.sin() / cos() Javadoc:
Parameters:
a - an angle, in radians.
Returns:
the sine of the argument.