Particle pile algorithm - java

I'm creating a game which has around 3000 particles that fall into a pile. The particles are each a pixel and i just use a boolean[][] to set and check which pixel is clear. Right now i am using this code
if (!isFalling(m)) {
if (isClear(getX() + 1, getY()) && isClear(getX() + 1, getY() - 1))
setX(getX() + 1);
else if (isClear(getX() - 1, getY()) && isClear(getX() - 1, getY() - 1)
setX(getX() - 1);
}
the problem is that this code gives me a very strict pyramid shape which doesnt look very natural. I want it to look something like salt would if you poured it into a pile. My question is, does anyone know of an algorithm or a better way to simulate particle piles?
Any help would be greatly appreciated.
Solution:
I have found a nice article here

You've taken on a big task :) It's not just how to calculate and draw the particles, it's the physics which describe how they should move.
Take a look at this for a starter:
http://www.daniweb.com/software-development/java/threads/426676/sand-game-problem-with-graphics
When Googling, try "particle generator" or "particle emitter".
Also see this question:
How do those java sand games keep track of so many particles?
The main thing you might be missing is to add randomness, some entropy, into your system.

So your function looks at particles which have settled to the bottom and asks if they can slide down the side, and then effects that motion if they can.
Do you have this in a loop? If so, you may be considering particles from the "bottom up" whereas the sliding motion may take place at any point on the pile. You could try shuffling the particle list prior to performing the loop, or repeatedly choosing random elements from the list until you get a low rate of settling.
In the case of a 2D array, you could try looping from different directions or finding other ways of mixing it up - again choosing pixels at random may not be a bad choice. Simulated annealing comes to mind.
Or, you could add a random check to your sliding condition. The particles should be semi-stable in their initial positions, so maybe there's only a 50% chance of them sliding down the side.
Hope this helps!

Related

How to draw circle and collide it? Android/Libgdx

Hey I'm currently programming a Game where the user (displayed as Spaceship) has to avoid Asteroids. First of all I want to do this is in a really simple way.
I would like to display the asteroids as circles and want them colliding to each other. Can someone answer me these Questions:
How do I draw a circle in Android/Libgdx/Java?
How do I create random movement of the circles?
How do I make these circles collide with each other and how to collide them with a Sprite in a simple way?
Btw, You don't have to answer all the questions :)
Well, you got a lot of beginner questions. No evil in that, but you should ask the google beforehand. I will answer your question with Canvas for the demonstration. Which contains prepared methods for basic shapes like circle.
First I would recommend you reading Android guide lines such as this
Second thing is collision. To check whether two circles are colliding you just take the distance of their centers (d) and compare it with the sum of their radii (r). Now if (d <= r) then collision is detected. Very good explanation is found here.
Third is the random movement. Here is the idea. Lets say we get random number for every circle for example from 0 to 100. If the number is below 50, its moving to right, else to the left. Of course you are welcome to add your creativity to this idea.

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.

A* with enemy awareness

I'm currently dabbling in Java AI programming, and trying an AI challenge. In the challenge, my AI is given 2 seconds to respond to the new game state. If these two seconds are exceeded without producing a response, my AI forfeits. The game consists of a grid with goals and enemies, each enemy being an independent AI generated by the game. I have implemented a standard A* to find the nearest available goal.
I would like my A* algorithm to increase the cost of squares near an enemy that could potentially prove dangerous, thus avoiding dangerous paths. I am considering a two-dimensional array containing the estimated loss of health for each square, limited to calculating within ~2 squares of each enemy (~5x5). Each turn, for each enemy this array would have a 5x5 square set to 0 and recalculated.
Assuming I write code that only does what it must and moves on... Will a two dimensional array of between 20x20 and 100x100 elements significantly effect execution time? Is a two dimensional array of estimated threat per square a good method of calculating cost in an A* algorithm so as to avoid enemies?
UPDATE:
I got it working absolutely perfectly. The cost function I used:
For each enemy
Calculate manhattan distance
If 0 or 1, cost += absolute(enemy health - health) / 5
Else if 2, cost += absolute(enemy heath - health) / 10
Else cost += 0
Using it, I saw some really impressive pathfinding and moves; the bot would often take calculated risks where there were no other moves to get to a goal, but basically avoided enemies otherwise. I was thoroughly impressed with how insignificant the performance cost was of adding the heuristic. It's not a perfect solution for the game, but it showed me how robust A* can be.
A* is generally used for pathfinding, but I'm going to modify it for the purpose of a game state lookahead. I'm pretty sure that turns it into a minimax algorithm.
If you are only calculating the content of your array once and the calculation
for each cell is something simple like checking a few adjacent cells for enemies then
a 100x100 array is no work at all relative to your time constraints.
Given the information in your post it sounds like a good idea to me.

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).

Implementing AI to hide behind obstacles

I am developing an AI simulation of predator and prey. I would like to simulate the AI hiding behind obstacles, if it is being chased. But I am still trying to figure out the best way to implement this.
I was thinking along the lines of checking on which side of the obstacle the predator is on and trying to go on the opposite side. Maybe using the A* path finding algorithm to ensure that it gets there using the shortest path.
Now the main reason I am writing is in case somebody is able to point me in the right direction of implementing this (maybe somebody has done this before) or have any other good ideas how to implement it. I have never done anything like this before in terms of programming AI or making any game.
All the obstacles are either horizontal or vertical squares/rectangles.
Please note that the circle in red is the predator while the circle in green is the prey being chased.
I can't give any code off the top of my head, but I can tell you a few things:
First, you need to define the goal of this program. For this case, it is to get the AI to hide behind an obstacle, keeping the user and the AI on opposite sides whenever possible.
Next, you need to decide what needs to be done inside the code (without writing any real code) to accomplish this goal. For instance:
We need to determine what "zone" of the scene is considered "behind the obstacle"
Next, we need to determine a path for the AI to get to that zone without going through the obstacle.
Lastly, we need to add some sort of delay to this so the AI doesn't constantly change its mind for every pixel the user moves across the screen
This isn't per se an easy problem, but it is certainly achievable without breaking too much of a sweat. I'd recommend you find a way, even if it is slow and requires a ton of code, then write the code for it, and lastly refine. If you worry about refinement, then you never get any of the problem solved.
HINT: Determine a vector that points from the player to the middle of the obstacle. Then, multiply the vector by 2 and add it to the position of the player and that gives you a point on the other side of the obstacle (assuming it is a rectangle). Apply a Math.min() or Math.max() restrictor to the x and y values you get to keep the AI as close or far from the obstacle as you wish. That should be a decent start! :)
Update -- I decided to add some code!
// This assumes a few variables:
int obstacleCenterX, obstacleCenterY;
int aiX, aiY, aiWalkSpeed;
int predatorX, predatorY;
private void updateAIMovement() {
int slope_x = obstacleCenterX - predatorX;
int slope_y = obstacleCenterY - predatorY;
int destination_x = predatorX + (slope_x * 2);
int destination_y = predatorY + (slope_y * 2);
if(aiX != destination_x){
aiX += (slope_x / Math.abs(slope_x)) * aiWalkSpeed;
}
if(aiY != destination_y){
aiY += (slope_y / Math.abs(slope_y)) * aiWalkSpeed;
}
}
I have not tested anything at all, but I think this might be somewhat of a right path to take. I could have done A LOT to improve just that little code snippet, but I didn't (such as some trig to make sure the player moves at a true speed when going diagonally, etc...)
Hopefully this helps a little!
I would check if there is something crossing the direct line between x and each observer. If it is, x is hidden.

Categories

Resources