Java move player smoothly from one point to another - java

All I need is to claculate the new coordinites of a player based on a click and have the player move towards it smoothly. For example player is at (20, 20) and you click at (50, 80) how would i get it to move smoothly. I have tried many different thing mostly based on the pythagorean formula trying to calculate the new coord's by finding the hypotenuse then finding the same triangle with a smaller hypotenuse but there must be an easier way.

You can:
Calculate the slope of the line segment formed by the origin and destination.
For each time period until you reach the destination, adjust the new coordinate based on the slope calculated in step 1.

Although I program in javascript, you should be able to read and understand it
function move(x1,y1,x2,y2,speed){//executed each time frame. Returns coords as array [x,y]
if(!speed)speed=1;
var dis=Math.sqrt(Math.pow(x1-x2)+Math.pow(y1-y2));
return [(x1-x2)/dis*speed,(y1-y2)/dis*speed];
}
The speed is constant at however many units per frame and it will stop when it reaches its destination. It might shake a little but that can be easily fixed.
EDIT: I forgot to mention. This function returns velocity. Not the coordinates

Related

Motion according by an angle Java Graphic

I am creating a simulation of a crowd using Java Swing and Java Graphics2D. I have a certain number of pedestrians that must reach some waypoints and I am having troubles with their motion.
The movement of each pedestrian now is very simple, it is something like this:
if (goalPosition.x > pedestrian.position.x) {
pedestrian.position.x++;
}
else
pedestrian.position.x--;
if (goalPosition.y > pedestrian.position.y) {
pedestrian.position.y++;
}
else
pedestrian.position.y--;
I just increase/decrease by 1 the position of each pedestrian according to the position of the goal to reach.
The problem is that i need to make them walk towards the goal in a straight line, I tried to compute angles and use trigonometry, but the problem with that approach is that I can't update the position of a pedestrian using a double value, because later each pedestrian is drawn using:
g2D.fillOval(pedestrian.position.x, pedestrian.position.y, ENTITY_SIZE, ENTITY_SIZE);
That accepts only integer positions.
Any idea of how I can update my code? Thanks

Physics circle collisions popping and sliding against bounds

In Java, I'm writing a mobile app for Android to interact with some dynamic balls with some classes I wrote myself. Gravity is determined on the tilt of the phone.
I noticed when I have a bunch of balls bunched up in a corner that some of them will begin to jitter, or sometimes slide while colliding with other balls. Could this be because I'm executing steps in the wrong order?
Right now I have a single loop going through each ball to:
Sim an iteration
Check collisions with other balls
Check collisions against scene bounds
I should add that I have friction with the bounds and when a ball to ball collision occurs, just to lose energy.
Here's a portion of code of how collision is being handled:
// Sim an iteration
for (Ball ball : balls) {
ball.gravity.set(gravity.x, gravity.y);
if (ball.active) {
ball.sim();
// Collide against other balls
for (Ball otherBall : balls) {
if (ball != otherBall) {
double dist = ball.pos.distance(otherBall.pos);
boolean isColliding = dist < ball.radius + otherBall.radius;
if (isColliding) {
// Offset so they aren't touching anymore
MVector dif = otherBall.pos.copy();
dif.sub(ball.pos);
dif.normalize();
double difValue = dist - (ball.radius + otherBall.radius);
dif.mult(difValue);
ball.pos.add(dif);
// Change this velocity
double mag = ball.vel.mag();
MVector newVel = ball.pos.copy();
newVel.sub(otherBall.pos);
newVel.normalize();
newVel.mult(mag * 0.9);
ball.vel = newVel;
// Change other velocity
double otherMag = otherBall.vel.mag();
MVector newOtherVel = otherBall.pos.copy();
newOtherVel.sub(ball.pos);
newOtherVel.normalize();
newOtherVel.mult(otherMag * 0.9);
otherBall.vel = newOtherVel;
}
}
}
}
}
If this is the only code that checks for interactions between balls, then the problem seems pretty clear. There is no way for a ball to rest atop another ball, in equilibrium.
Let's say that you have one ball directly on top of another. When you compute the acceleration of the top ball due to gravity, you should also be doing a collision check like the one you posted, except this time checking for dist <= ball.radius + otherBall.radius. If this is the case, then you should assume a normal force between the balls equal to that of gravity, and negate the component of gravity in line with the vector connecting the two balls' centers. If you fail to do this, then the top ball will accelerate into the bottom one, triggering the collision code you posted, and you'll get the jitters.
Similar logic must be used when a ball is in contact with a scene bound.
Since I've been experimenting with my own Phys2D engine (just for fun), I know you're talking about. (Just in case - you may check my demo here: http://gwt-dynamic-host.appspot.com/ - select "Circle Collisions Demo" there, and corresponding code here: https://github.com/domax/gwt-dynamic-plugins/tree/master/gwt-dynamic-main/gwt-dynamic-module-bar).
The problem is in a nature of iterations and infinite loop of colliding consequences. When e.g. ball is reached the scene corner, it experiences at least 3 vectors of force: impulse of bounce from the wall, impulse of bounce from the floor and impulse of gravity - after you summarize all 3 impulses, reduce it according loosing energy algorithm, you have to have the new vector where your ball should be. But, e.g. this impulse directs it into wall - then you have to recompute the set of vectors again according to all the stuff: energy of bounce, impulses, gravity, etc. Even in case if all these impulses are small, you never get all of them 0, because of precision of doubles and your tolerance comparison constants - that because you have the "jitter" and "sliding" effects.
Actually, most of existing 2D engines have these effects one kind or another: you may see them here: http://brm.io/matter-js/demo/#wreckingBall or here: http://box2d-js.sourceforge.net/index2.html - they actually just make the small impulses to be absorbed faster and stop iterating when the whole system becomes more or less stable, but it is not always possible.
Anyway, I'd just recommend do not reinvent your own wheel unless it is just for your fun - or for your better understanding this stuff.
For last one (JFF) - here is good tutorial: http://gamedevelopment.tutsplus.com/tutorials/how-to-create-a-custom-2d-physics-engine-the-basics-and-impulse-resolution--gamedev-6331
For real things, I'd recommend to use the existing engines, e.g. Unity (https://unity3d.com/learn/tutorials/modules/beginner/2d/physics2d) or Box2d (http://box2d.org/)
Hope this helps.
Iterating through all the balls and changing the balls position for each iteration is probably the cause for the instability, you move a ball left to avoid collision on the right, and then you pushed the ball into another ball on the left, and then the left ball tries to push it back again.
From the top of my head I could recommend trying to sum up all the forces on each ball before doing anything about positioning. And if you iterate from the ball "on top" (furthest away from gravity source/direction) you can probably achieve a stable situation.
Basically, the top ball needs to first calculate forces between itself and the ball(s) under it, plus gravity, then the ball under will know how much force is coming from the top ball, and added with gravity it would also add to the force of which it is pushing the balls under it. When all balls know the forces they're pushed with you can transform that force into motion.
The way you are simulating the physics of the balls is bound to cause instabilities. Your collision resolution tries to separate the balls by projecting one of them in the opposite direction by the collision depth. This may fix the overlap for those two balls but chances are(especially when the balls are stacked) that the ball is now overlapping with another ball.
There are many ways to fix penetration. One of the simplest ways is to add a "bias" or a bit of a push to both bodies to force them to separate over the next couple of frames. This allows that energy to propagate and force all of the bodies apart. Problem is, the bias will often overestimate and cause a bit of a bounce. To fix that problem I'd recommend reading up on sequential impulse.
Making physics look realistic is not as easy as it may seem. Unless you don't mind instabilities I'd recommend spending some time reading up on different techniques or using an engine such as Box2D.

Let an Enemy follow a path with the same speed

I started programming a game in java. I have Enemys and a Player, a basic 2D game, thats to get experience for the first time.
Now i wanted the Enemys to follow a path, which i can draw in to a "level editor".
I have a JPanel, a mouseMoveListener, and on click the Path2D starts saving the mouseMove Points to a Path2D.Double Object.
After that, i implemented the following method to make the enemys following this path:
public void forward(){
if(!pathIterator.isDone()){
pathIterator.currentSegment(current);
x = current[0];
y = current[1];
pathIterator.next();
}
else {
dead = true;
}
}
I think its clear what happens now: The Enemy is following, but the speed is that i moved the mouse with. So if i move to Mouse to fast, the enemy just.. "jumps" from one point to an other. To slow, its "sneaking" over that points. (And because im not an Robot, i cannot move the Mouse with the same speed ^^)
Talking of Robot: Yes, i could let a awt.Robot move my Mouse. But this isnt really possible too, because i have to draw complicated paths, which dont have any visible mathematics behind.
So, i want let this Enemys to move on this path with the same speed. My Problem: I don't know where to implement a "fix". I have 2 Ideas:
Maybe i could work on the Path creation: Instead of just adding the Points to the Path2D, maybe i could calculate points between the points where i moved to fast, or deleting points which are to near by each other. But: First, I don't know how to calculate this, (Is there any maths logic to achieve this?) And Second, when i do this i probably would'nt be able to change the speed of the enemys ingame, and that would be bad
The second idea i have, is to calculate the points between (oder the points to jump over), this should happen every frame, relative to the actual speed. But here im not experienced enough in maths to.
So, are that ways possible, and if yes, has someone an idea how to calculate this?
And, if not, what other possibilitys i have to achieve this?
Thank you, and sorry for the bad english!
All you need to do is define the speed of movement of the enemy inside the enemy class.
When it works out the next point to move to then create a direction vector by subtracting the current position from the new position.
Normalize the direction vector (so it is length 1) then multiply it by the speed and the tpf (time per frame).
Move by that amount instead of jumping to the next point.
(Note if the points are very close together or the framerate is low this can cause it to overshoot a bit, it should be fine though).

Heuristic function for astar

I need a good heuristic function for A star for the pen plotter/TSP, where each state of my system has:
Path distance, that has been traveled
Point where the pen is at currently
Pen up/down
The "pen up/down" refers to the state where, you have drawn a line just then or you are moving to a point to start a new line.
Seeing as I have to travel through every point at some stage, the final goal state could be any point making any of the heuristics I've found on the internet impossible to use properly. I have tried the following, but failed to get a good heuristic from it:
(g(x) divided by the sum of the total distance traveled) * number of states remaining
(assuming you are alternating between drawing a line or moving to a new point to draw a line)
I've also tried
the euclidean distance between the current state and the goal state (find the closest possible goal state).
This does not work since it gives you a heuristic of 0 because any state/point can be the goal state
Taxicab Geometry may be a solution. I've experimented with code that uses the results for completing a sliding tile puzzle

Detecting Singularities in a Graph

I am creating a graphing calculator in Java as a project for my programming class. There are two main components to this calculator: the graph itself, which draws the line(s), and the equation evaluator, which takes in an equation as a String and... well, evaluates it.
To create the line, I create a Path2D.Double instance, and loop through the points on the line. To do this, I calculate as many points as the graph is wide (e.g. if the graph itself is 500px wide, I calculate 500 points), and then scale it to the window of the graph.
Now, this works perfectly for most any line. However, it does not when dealing with singularities.
If, when calculating points, the graph encounters a domain error (such as 1/0), the graph closes the shape in the Path2D.Double instance and starts a new line, so that the line looks mathematically correct. Example:
(source: imagesocket.com)
However, because of the way it scales, sometimes it is rendered correctly, sometimes it isn't. When it isn't, the actual asymptotic line is shown, because within those 500 points, it skipped over x = 2.0 in the equation 1 / (x-2), and only did x = 1.98 and x = 2.04, which are perfectly valid in that equation. Example:
(source: imagesocket.com)
In that case, I increased the window on the left and right one unit each.
My question is: Is there a way to deal with singularities using this method of scaling so that the resulting line looks mathematically correct?
I myself have thought of implementing a binary search-esque method, where, if it finds that it calculates one point, and then the next point is wildly far away from the last point, it searches in between those points for a domain error. I had trouble figuring out how to make it work in practice, however.
Thank you for any help you may give!
You could use interval arithmetic ( http://en.wikipedia.org/wiki/Interval_arithmetic ) and calculate the interval of the function on each interval [x(i), x(i+1)]. If the resulting interval is infinite, skip that line segment. Speed-wise this should only be a couple times slower than just evaluating the function.
I think you are mostly on the right track.
I don't think figure 2 is mathematically incorrect.
For bonus points, you should have a routine which checks the diff between two consecutive values y1 & y2, and if it is greater than a threshold, inserts more points between y1 and y2, until no diff is greater than the threshold. If this iterative rountine is unable to get out of the while loop after 10 iterations or so, then that indicates presence of a singularity, and you can remove the plot between y1 and y2. That will give you figure 1.
If morpehus's solution is too slow for you, you can consider all the absolute values of jumps between two consecutive function values, and try to identifies large outliers -- these will be the infinite jumps.
If you decide to try this, and need help, leave a comment here.
I finally figured out a way to have singularities graphed properly.
Essentially what I do is for every point on the graph, I check to see if it is inside the visible graphing clip. If I hit a point on the graph that is outside the visible clip, I graph that first point outside the clip, and then stop graphing any invisible points after that.
I keep calculating points and checking if they are inside the visible clip, not graphing ones that are outside the clip. Once I hit a point that is inside the clip again, I graph the point before that point, and then graph the current point.
I keep doing this until I've graphed the entire line. This creates the illusion that the entire line is begin drawn, when only the visible parts are.
This won't work if the window is large and the actual graph size in pixels is small, but it does suffice for me.

Categories

Resources