What algorithm to use for finding empty areas in 2D? - algorithm

I have 3d elements (triggers) that spawn content boxes when clicking on them. I am searching for an algorithm that spawns elements in an empty area close to the trigger. A 2d approach might be enough since the content boxes need to face the user.
The spawned content box should neither overlap the trigger object, nor other 3d elements / contentboxes.
Example:
If the trigger is a long vertical tube, the first contentbox might spawn to the left of it, the next one would spawn to the right since the left is already occupied with contentbox 1. The third contentbox might then spawn above/below the first contentbox or if there is other stuff in the way then to the left of the first contentbox.
This should work in realtime, it doesnt have to be the actual closest point but should aim for keeping everything closely together. I assume that this is a problem many people solved before me but somehow I couldnt find sufficient information, maybe I am lacking the correct search terms, I am happy to hear about different approaches, hints & ideas..
Thanks
friday

Try to create a grid on the existed points in the plane or space. This grid could be two perpendicular line on each existed point. After that, create a tree to search on this space. Or just create a kd-tree on these points. Youcan find more about these in computational geometry context.

Related

Making Algorithm to Find Most Move Efficient Solution in a Complicated 2d Puzzle Game

I'm trying to make an algorithm of any sort that can find the solution with the lowest move count. I'm coding in GML using GMS2 and it's for a game that I'm making myself.
This is a picture of the most simple level
The reason I call it a complicated 2d puzzle game is because of how many types of blocks there are. The goal is to connect the two blocks and the player gets a trophy for solving it in a low move count, but I don't want to have to find the most efficient solutions by hand for every level, especially some of the super complicated levels.
This is an example of a level with all block types in it
The black boxes with an X on them are immovable and act as obstacles
The two blocks you're supposed to connect and the small blue blocks are simple movable blocks and can be moved in any of the four cardinal directions as long as the space is open
The long blue blocks act the same way but require an open space their same size to move into a spot
The red blocks act as a normal movable block, but cannot be placed next to each other. They can still be diagonal from each other though
And the green blocks can only be moved in the directions indicated on the block, meaning only left and right or only up and down
My first thought was to make a depth first search algorithm to just brute force all possible game states until it finds the quickest solution but I'm unsure of how to pull that off.
If anyone has any ideas for methods I could use or information that could help at all then I'm open to all feedback since I don't really know much about algorithms or machine learning at all, thanks in advance!
The standard approach is a breadth-first search. Looking at this hashmap and native queues I believe you can code it in GML, though that wouldn't be my first choice. (Python would be because you can have complex objects as dictionary keys. Dictionary being what Python calls a hashmap. Without that you'll need to serialize/deserialize objects to use them as keys. Serialize being a complicated word meaning, "write out a text representation". Ideally a compact text representation.)
The idea looks like this:
Create hashmap of position and last move
initialize it with start position and last move is none
put start position into a queue of positions to analyze
while stuff in queue and not yet solved:
pop position from queue
for each valid move from position:
if resulting position is solved:
it is solved and we have final position
if resulting position is NOT in hashmap:
add position + move to hashmap
add position to queue
if no final position:
there is no answer
else:
path = []
prev_move = hashmap of final position
while prev_move is not none:
add prev_move to start of path
unto prev_move from final position to get new final position
And if it is solvable, then path will wind up being the shortest path from the starting position to any position where it is solved.
Note that the number of possible positions explodes, so you can only solve fairly small puzzles. With ideas like A* search you can make this slightly more efficient, but given how much backtracking tends to be involved, not much.

Indefinitely move objects around randomly without collision

I have an application where I need to move a number of objects around on the screen in a random fashion and they can not bump into each other. I'm looking for an algorithm that will allow me to generate the paths that don't create collisions and can continue for an indefinite time (i.e.: the objects keep moving around until a user driven event removes them from the program).
I'm not a game programmer but I think this looks like an AI problem and you guys probably solve it with your eyes closed. From what I've read A* seems to be the recommended 'basic idea' but I don't really want to invest a lot of time into it without some confirmation.
Can anyone shed some light on an approach? Anti-gravity movement maybe?
This is to be implemented on iOS, if that is important
New paths need to be generated at the end of each path
There is no visible 'grid'. Movement is completely free in 2D space
The objects are insects that walk around the screen until they are killed
A* is an algorithm to find the shortest path between a start and a goal configuration (in terms of whatever you define as short: common are e.g. euclidean distance, cost or time, angular distance...). Your insects seem not to have a specific goal, they don't even need a shortest path. I would certainly not go for A*. (By the way, since you are having a dynamic environment, D* would have been an idea - still it's meant to find a path from A to B).
I would tackle the problem as follows:
Random Paths and following them
For the random paths I see two methods. The first would be a simple random walk (click here to see a nice 2D animation with explanations), which can suffer from jittering and doesn't look too nice. The second one needs a little bit more detailed explanations.
For each insect generate four random points around them, maybe starting on a sinusoid. With a spline interpolation generate a smooth curve between those points. Take care of having C1 (in 2D) or C2 (in 3D) continuity. (Suggestion: Hermite splines)
With Catmull-Rom splines you can find your configurations while moving along the curve.
An application of a similar approach can be found in this blog post about procedural racetracks, also a more technical (but still not too technical) explanation can be found in these old slides (pdf) from a computer animations course.
When an insect starts moving, it can constantly move between the second and third point, when you always remove the first and append a new point when the insect reaches the third, thus making that the second point.
If third point is reached
Remove first
Append new point
Recalculate spline
End if
For a smoother curve add more points in total and move somewhere in the middle, the principle stays the same. (Personally I only used this in fixed environments, it should work in dynamic ones as well though.)
This can, if your random point generation is good (maybe you can use an approach similar to the one provided in the above linked blog post, or have a look at algorithms on the PCG Wiki), lead to smooth paths all over the screen.
Avoid other insects
To avoid other insects, three different methods come to my mind.
Bug algorithms
Braitenberg vehicles
An application of potential fields
For the potential fields I recommend reading this paper about dynamic motion planning (pdf). It's from robotics, but fairly easy to apply to your problem as well. You can just use the robots next spline point as the goal and set its velocity to 0 to apply this approach. However, it might be a bit too much for your simple game.
A discussion of Braitenberg vehicles can be found here (pdf). The original idea was more of a technical method (drive towards or away from a light source depending on how your motor is coupled with the photo receptor) and is often used to show how we apply emotional concepts like fear and attraction to other objects. The "fear" behaviour is an approach used for obstacle avoidance in robotics as well.
The third and probably simplest method are bug algorithms (pdf). I always have problems with the boundary following, which is a bit tricky. But to avoid another insect, these algorithms - no matter which one you use (I suggest Bug 1 or Tangent Bug) - should do the trick. They are very simple: Move towards your goal (in this application with the catmull-rom splines) until you have an obstacle in front. If the obstacle is close, change the insect's state to "obstacle avoidance" and run your bug algorithm. If you give both "colliding" insects the same turn direction, they will automatically go around each other and follow their original path.
As a variation you could just let them turn and recalculate a new spline from that point on.
Conclusion
Path finding and random path generation are different things. You have to experiment around what looks best for your insects. A* is definitely meant for finding shortest paths, not for creating random paths and following them.
You cannot plan the trajectories ahead of time for an indefinite duration !
I suggest a simpler approach where you just predict the next collision (knowing the positions and speeds of the objects allows you to tell if they will collide and when), and resolve it by changing the speed or direction of either objects (bounce before objects touch).
Make sure to redo a check for collisions in case you created an even earlier collision !
The real challenge in your case is to efficiently predict collisions among numerous objects, a priori an O(N²) task. You will accelerate that by superimposing a coarse grid on the play field and look at objects in neighboring cells only.
It may also be possible to maintain a list of object pairs that "might interfere in some future" (i.e. considering their distance and relative speed) and keep it updated. Checking that a pair may leave the list is relatively easy; efficiently checking for new pairs needing to enter the list is not.
Look at this and this Which described an AI program to auto - play Mario game.
So in this link, what the author did was using a A* star algorithm to guide Mario Get to the right border of the screen as fast as possible. Avoid being hurt.
So the idea is for each time frame, he will have an Environment which described the current position of other objects in the scene and for each action (up, down left, right and do nothing) , he calculate its cost function and made a decision of the next movement based on this.
Source: http://www.quora.com/What-are-the-coolest-algorithms
For A* you would need a 2D-Grid even if it is not visible. If I get your idea right you could do the following.
Implement a pathfinding (e.g. A*) then just generate random destination points on the screen and calculate the path. Once your insect reaches the destination, generate another destination point/grid-cell and proceed until the insect dies.
As I see it A* would only make sence if you have obstacles on the screen the insect should navigate around, otherwise it would be enough to just calculate a straight vector path and maybe handle collision with other insects/objects.
Note: I implemented A* once, later I found out that Lee's Algorithm
pretty much does the same but was easier to implement.
Consider a Hamiltonian cycle - the idea is a route that visits all the positions on a grid once (and only once). If you construct the cycle in advance (i.e. precalculate it), and set your insects off with some offset between them, they will never collide, simply because the path never intersects itself.
Also, for bonus points, Hamiltonian paths tend to 'wiggle about', and because it's a loop you can predict (and precalculate) the path into the indefinite future.
You can always use the nodes of the grid as knot points for a spline to smooth the movement, or even randomly shift all the points away from their strict 2d grid positions, until you have the desired motion.
Example Hamiltonian cycle from Wikimedia:
On a side note, if you want to generate such a path, consider constructing a loop through many points and just moving the points around in such a manner that they never intersect an existing edge. With some encouragement to move into gaps and away from each other, they should settle into some long, never-intersecting path. Store the result and use for your loop.

Plat former Game - A realistic path-finding algorithm

I am making a game and i have come across a hard part to implement into code. My game is a tile-bases platformer with lots of enemies chasing you. basically, in theory, I want my enemies to be able to, every frame/second/2 seconds, find the realistic, and shortest path to my player. I originally thought of A-star as a solution, but it leads the enemies to paths that defy gravity, which is not good. Also, multiple enemies will be using it every second to get the latest path, and then walk the first few tiles of it. So they will be discarding the rest of the path every second, and just following the first few tiles of it. I know this seems like a lot, to calculate a new path every second, all at the same time, if their is more than one enemy, but I don't know any other way to achieve what i want.
This is a picture of what I want:
Explanation: The green figure is the player, the red one is an enemy. the grey tiles are regular, open, nothing there tiles, the brown tiles being ones that you can stand on. And finally the highlighted yellow tiles represents the path that i want my enemy to be able to find, in order to realistically get to the player.
SO, the question is: What realistic path-finding algorithm can i use to acquire this? While keeping it fast?
EDIT*
I updated the picture to represent the most complicated map that their could be. this map represents what the player of my game actually sees, they just use WASD and can move around and they see themselves move through this 2d plat-former view. Their will be different types of enemies, all with different speeds and jump heights. but all will have enough jump height and speed to make the jumps in this map, and maneuver through it. The maps are generated by simply reading an XML file that has the level data in it. the data is then parsed and different types of tiles are placed in the tile holding sprite, acording to what the XML says. EX( XML node: (type="reg" graphic="grass2" x="5" y="7") and so the x and y are multiplied by the constant gridSize (like 30 or something) and they are placed down accordingly. The enemies get their frame-by-frame instruction from an AI class attached to them. This class is responsible for producing this path and return the first direction to the enemy, this should only happen every second or so, so that the enemies don't follow a old, wrong path. Please let me know if you understand my concept, and you have some thought/ideas or maybe even the answer that i'm looking for.
ALSO: the physics in this game is separate from the pathfinding, they work just fine, using a AABB vs AABB concept (the player and enemies also being AABBs).
The trick with using A* here is how you link tiles together to form available paths. Take for example the first gap the red player would need to cross. The 'link' to the next platform (aka brown tile to the left) is actually a jump action, not a move action. Additionally, it's up to you to determine how the nodes connect together; I'd add a heavy penalty when moving from a gray tile over a brown tile to a gray tile with nothing underneath just for starters (without discouraging jumps that open a shortcut).
There are two routes I see personally: running a quick prediction of how far the player can jump and where they'd jump and adjusting how the algorithm determines node adjacency or accept the path and determine when parts of the path "hang" in the air (no brown tile immediately below) and animate the enemy 'jumping' to the next part of the path. The trick is handling things when the enemy may pass through brown tiles in the even the path isn't a parabola.
I am not versed in either solution; just something I've thought about.
You need to give us the most complicated case of map, player and enemy behaviour (including jumping up and across speed) that you are going to either automatically create or manually create so we can give relevant advice. The given map is so simple, put the map in an 2-dimensional array and then the initial player location as an element of that map and then first test whether lower number column on the same row is occupied by brown if not put player there and repeat until false then same row higher column and so on to move enemy.
Update: from my reading of the stage generation- its sometime you create- not semi-random.
My suggestion is the enemy creates clones of itself with its same AI but invisible and each clone starts going in different direction jump up/left/right/jump diagonal right/left and every time it succeeds it creates a new clone- basically a genetic algorithm. From the map it seems an enemy never need to evaluate one path over another just one way fails to get closer to the player's initial position and other doesn't.

Algorithm for items placement

I have a "complex" problem where I have a bunch of tooltips (orange) on top of elements (black) that can be randomly placed on screen. The tooltips are a big square with a triangle in the middle of one of it's 4 sides pointing though the element direction. By default, the triangle will be in the middle of the element, but can be moved as long as it stay close to it, so we can't easily understand it refer to this element and not another one.
The problem is, the tooltip must NOT overlap each other, and can't be out of screen.
Image of my tooltip problem
I thought about first placing every tooltips to their default position (triangle pointing down), and then check if they are out of screen or overlap another one, and if so, try another position. But using this technique (which is probably the simplest one), I do not guarantee the best placement since once a tooltip has been placed, I will not replace him if another one can't fit anywhere otherwise it become too complex.
Does someone have any tips/idea how to deal with this type of problem?
Thanks!!
This looks like an instance of the map labelling problem. Wikipedia has an article about it.
You could place all the tooltips using some sort of physical simulation of repulsive electrical charges, similar to what is done in some algorithms for drawing graphs. You could model each tooltip as an object attached with a soft spring to its black box, while simulating a strong repulsive force between all the tooltips and between a tooltip and the edge of the image. You calculate all the forces and move the tooltips iteratively, until all positions converge. You could play with making the force scale as inverse square, inverse cube, etc to find nice results.
This might be a bit of work to implement, but should probably give decent results for simple cases. It is probably impossible to guarantee that a good solution always exists, since if you add too many tooltips, your image will be full.

Finding Room for a Shape on a Grid

I'm working on a game where you have an 8x12 grid where each cell is the same size and all the cells are directly next to one another.
You drag around various Tetris-like shapes and place them on the grid in valid locations, a valid location being one where all the cells that the shape will occupy are not occupied by some other shape.
My problem is that I'm not sure how to search the grid space for valid locations. I've been searching for an algorithm that will solve this sort of problem, but I have come up empty handed thus far. It seems like it should be pretty straightforward to detect valid locations, but I have not been able to come to a successful solution.
Any processes, algorithm suggestions, or ideas for how to go about solving this would be extremely helpful. Thanks!
EDIT:
Here is the expected functionality: When the shape is in a valid location, it can be dragged between valid locations freely and follows the mouse pointer. However, when you try to drag the shape into an invalid area (ie movement in the direction specified would place one or more blocks of the shape in invalid locations), it stays in the last valid location.
At this point, when the mouse is in an invalid area, I want to do some "predictive" movement so that if the player moves the mouse cursor near a valid position, the shape then "snaps" into place, say if the valid position is two grid spaces away.
Thanks for your suggestion so far; I hadn't thought of that method!
As described, the algorithm would be quite simple. Arbitrarily choose a starting block on your shape, and try to match it to each open cell of the grid. If "drawing" the shape with the block aligned with the current cell doesn't cause a collision, you've found a valid position.

Resources