Raycasting in all direction from the source in three js - three.js

I am working with RayCasting in three js from couple of days and have understood how it works.
at the moment I am able to intersect the object using raycasting but I am up with one problem.
I am trying to find if there is any obstacle intersecting my 5 meter away from my source and I am looking to check this 5 meter in all the direction(similar like a boundary of 5 meters around the object).
right now with what I am doing it only checks at one.
so can someone help me how can I achieve this ?

Using raycasting is not a precise and performant approach for this kind of collision detection since you would have to cast an infinite number of rays to produce a 100% reliable result.
You should work with bounding volumes instead and perform intersection tests between those. three.js provides a bounding sphere and AABB implementation in the core which are sufficiently tight bounding volumes for many use cases. You can also give the new
OBB class a try which is located in the examples. All three classes provide methods for intersection tests between all types.

Related

Nearest neighbours

I'm trying to find a lightweight way to find nearby objects in three.js.
I have a bunch of cubes, and I want each cube to be able to determine the nearest cubes to it on demand.
Is there a better way to do this than just iterating through all objects and calculating the distance between them? I know the renderer does something similar to what I want when it sorts to find the order to render with, but I'm not getting too far just trying to read the three.js code.
The renderer is doing the same thing you're describing but you may want to use KDTrees in your case.
Have a look at this example:
http://threejs.org/examples/webgl_nearestneighbour.html

What is the best approach for making large number of 2d rectangles using Three.js

Three.JS noob here trying to do 2d visualization.
I used d3.js to make an interactive visualization involving thousands of nodes (rectangle shaped). Needless to say there were performance issues during animation because Browsers have to create an svg DOM element for every one of those 10 thousand nodes.
I wish to recreate the same visualization using WebGl in order to leverage hardware acceleration.
Now ThreeJS is a library which I have choosen because of its popularity (btw, I did look at PixiJS and its api didn't appeal to me). I am wanting to know what is the best approach to do 2d graphics in three.js.
I tried creating one PlaneGeometry for every rectangle. But it seems that 10 thousand Plane geometries are not the say to go (animation becomes super duper slow).
I am probably missing something. I just need to know what is the best primitive way to create 2d rectangles and still identify them uniquely so that I can interact with them once drawn.
Thanks for any help.
EDIT: Would you guys suggest to use another library by any chance?
I think you're on the right track with looking at WebGL, but depending on what you're doing in your visualization you might need to get closer to the metal than "out of the box" threejs.
I recommend taking a look at GLSL and taking a look at how you can implement your visualization using vertex and fragment shaders. You can still use threejs for a lot of the WebGL plumbing.
The reason you'll probably need to get directly into GLSL shader work is because you want to take most of the poly manipulation logic out of javascript, at least as much as is possible. Any time you ask js to do a tight loop over tens of thousands of polys to update position, etc... you are going to struggle with CPU usage.
It is going to be much more performant to have js pass in data parameters to your shaders and let the vertex manipulation happen there.
Take a look here: http://www.html5rocks.com/en/tutorials/webgl/shaders/ for a nice shader tutorial.

Collision Detection in a Vector Based 2D Platformer

like many others before, I'm coding a 2D platformer at the moment, or more precise on an Engine for that. My question is about collision detection and especially the reactions to collision.
It's vital to me to have surfaces that are NOT tile based, because the world of the platformer has urgend need of surfaces that are not straight.
What do you think is the best approach for implementing such?
I've already come to a solution, but I'm only about 95% satisfied with it.
My Entity is component based so at first it calculates all the movement. Horizontal position change. Falling. Jumping speed; all that. Then it stores these values temporarily; accessible to the Collision component.
This one adds 4 hitpoints to the entity. Two for the floor collision and two for the wall collision.
Like this
(source: fux-media.com)
I first check against the floor. When there IS collision, I iterate collision detections upwards until there is no more collision.
The I reset the Entity to this point. If both ground hitpoints collide, I reset the Entity to the lowest point to avoid the Entity floating in the air.
Then I check against the wall with the upper hitpoints. Basically, if it collides, I do the same thing as above, just horizontally.
If works quite well. Very heavy ascensions are treated like a wall and very low ascensions are just climbed. But in between, when the ascensions are around 45 degree, it behaves strange. It does not quite feel right.
Now, I could just avoid implementing 45 degree walls in my game, but that would just not be clean, as I'm programming an engine that is supposed to work right no matter what.
So... how would you implement this, algorithmically?
I think you're on the right track with the points. You could combine those points to form a polygon, and then use the resulting polygon to perform collision detection.
Phys2D is a library that happens to be in Java that does collision between several types of geometric primitives. The site includes downloadable/runnable demos on what the library is capable of.
If you look around, you can find 2D polygon collision detection implementations in most common languages. With some study, an understanding of the underlying geometry calculations, and some gusto, you could even write your own if you like.

Collisions in computer games

I have a general questions regarding techniques, or approaches used in computer games to detect particles (or objects collisions). Even in a smiple examples, like currently popular angry birds, how is it programmetically achieved that the game knows that an object hits another one and works out it trajectory, while this object can hit others etc. I presume it is not constantly checking states of ALL the objects in the game map...
Thanks for any hints/answers and sorry for a little dummy/general question.
Games like Angry Birds use a physics engine to move objects around and do collision detection. If you want to learn more about how physics engines work, a good place to start is by reading up on Box2D. I don't know what engine Angry Birds uses, but Box2D is widely used and open-source.
For simpler games however you probably don't need a physics engine, and so the collision detection is fairly simple to do and involves two parts:
First is determining which objects to test collision between. For many small games it is actually not a bad idea to test every single object against every other object. Although your question is leery of this brute-force approach, computers are very fast at routine math like that.
For larger scenes however you will want to cull out all the objects that are too far away from the player to matter. Basically you break up the scene into zones and then first test which zone the character is in, then test for collision with every object in that zone.
One technique for doing this is called "quadtree". Another technique you could use is Binary Space Partitioning. In both cases the scene is broken up into a lot of smaller pieces that you can use to organize the scene.
The second part is detecting the collision between two specific objects. The easiest way to do this is distance checks; just calculate how far apart the two objects are, and if they are close enough then they are colliding.
Almost as easy is to build a bounding box around the objects you want to test. It is pretty easy to check if two boxes are overlapping or not, just by comparing their coordinates.
Now bounding boxes are just rectangles; this approach could get more complex if the shapes you want to collide are represented by arbitrary polygons. Some basic knowledge of geometry is usually enough for this part, although full-featured physics engines can get into a lot more detail, telling you not just that a collision has happened, but exactly when and how it happened.
This is one of those hard to answer questions here, but here's a very basic example in 2D as a very basic example, in pseudo-code.
for-each sprite in scene:
for-each othersprite in scene:
if sprite is not othersprite & sprite.XY = othersprite.XY
collision = true;
else
collision = false;
Hopefully that should be enough to get your thought muscles working!
Addendum: Other improvements would be to assume an area around the XY instead of a precise location, which then gives you a sort of support for sprites with large areas.
For 3D theory, I'll give you the article I read a while ago:
http://www.euclideanspace.com/threed/animation/collisiondetect/index.htm
num1's answer covers most of what I would say and so I voted it up. But there are a few modifications/additional points I would make:
1) Bounding boxes are actually the second easiest way to test collision. The easiest way is distance checks; just calculate how far apart the two objects are, and if they are close enough then they are colliding.
2) Another common way of organizing the scene in order to optimize collision tests (ie. an alternative to BSP) is quadtrees. In either case, basically you break up the scene into zones and then first test which zone the character is in, then test for collision with every object in that zone. That way if the level is huge you don't test against every single object in the level; you can cull out all the objects that are too far away from the player to matter.
3) I would emphasize more that Angry Birds uses a physics engine to handle its collisions. While distance checks and bounding boxes are fine for most 2D games, Angry Birds clearly did not use either of those simple methods and instead relied on collision detection from their physics engine. I don't know what physics engine is used in that game, but Box2D is widely used and open-source.

How does 3D collision / object detection work?

I'v always wondered this. In a game like GTA where there are 10s of thousands of objects, how does the game know as soon as you're on a health pack?
There can't possibly be an event listener for each object? Iterating isn't good either? I'm just wondering how it's actually done.
There's no one answer to this but large worlds are often space-partitioned by using something along the lines of a quadtree or kd-tree which brings search times for finding nearest neighbors below linear time (fractional power, or at worst O( N^(2/3) ) for a 3D game). These methods are often referred to as BSP for binary space partitioning.
With regards to collision detection, each object also generally has a bounding volume mesh (set of polygons forming a convex hull) associated with it. These highly simplified meshes (sometimes just a cube) aren't drawn but are used in the detection of collisions. The most rudimentary method is to create a plane that is perpendicular to the line connecting the midpoints of each object with the plane intersecting the line at the line's midpoint. If an object's bounding volume has points on both sides of this plane, it is a collision (you only need to test one of the two bounding volumes against the plane). Another method is the enhanced GJK distance algorithm. If you want a tutorial to dive through, check out NeHe Productions' OpenGL lesson #30.
Incidently, bounding volumes can also be used for other optimizations such as what are called occlusion queries. This is a process of determining which objects are behind other objects (occluders) and therefore do not need to be processed / rendered. Bounding volumes can also be used for frustum culling which is the process of determining which objects are outside of the perspective viewing volume (too near, too far, or beyond your field-of-view angle) and therefore do not need to be rendered.
As Kylotan noted, using a bounding volume can generate false positives when detecting occlusion and simply does not work at all for some types of objects such as toroids (e.g. looking through the hole in a donut). Having objects like these occlude correctly is a whole other thread on portal-culling.
Quadtrees and Octrees, another quadtree, are popular ways, using space partitioning, to accomplish this. The later example shows a 97% reduction in processing over a pair-by-pair brute-force search for collisions.
A common technique in game physics engines is the sweep-and-prune method. This is explained in David Baraff's SIGGRAPH notes (see Motion with Constraints chapter). Havok definitely uses this, I think it's an option in Bullet, but I'm not sure about PhysX.
The idea is that you can look at the overlaps of AABBs (axis-aligned bounding boxes) on each axis; if the projection of two objects' AABBs overlap on all three axes, then the AABBs must overlap. You can check each axis relatively quickly by sorting the start and end points of the AABBs; there's a lot of temporal coherence between frames since usually most objects aren't moving very fast, so the sorting doesn't change much.
Once sweep-and-prune detects an overlap between AABBs, you can do the more detailed check for the objects, e.g. sphere vs. box. If the detailed check reveals a collision, you can then resolve the collision by applying forces, and/or trigger a game event or play a sound effect.
Correct. Normally there is not an event listener for each object. Often there is a non-binary tree structure in memory that mimics your games map. Imagine a metro/underground map.
This memory strucutre is a collection of things in the game. You the player, monsters and items that you can pickup or items that might blowup and do you harm. So as the player moves around the game the player object pointer is moved in the game/map memory structure.
see How should I have my game entities knowledgeable of the things around them?
I would like to recommend the solid book of Christer Ericson on real time collision detection. It presents the basics of collision detection while providing references on the contemporary research efforts.
Real-Time Collision Detection (The Morgan Kaufmann Series in Interactive 3-D Technology)
There are a lot of optimizations can be used.
Firstly - any object (say with index i for example) is bounded by cube, with center coordinates CXi,CYi, and size Si
Secondly - collision detection works with estimations:
a) Find all pairs cubes i,j with condition: Abs(CXi-CXj)<(Si+Sj) AND Abs(CYi-CYj)<(Si+Sj)
b) Now we work only with pairs got in a). We calculate distances between them more accurately, something like Sqrt(Sqr(CXi-CXj)+Sqr(CYi-CYj)), objects now represented as sets of few numbers of simple figures - cubes, spheres, cones - and we using geometry formulas to check these figures intersections.
c) Objects from b) with detected intersections are processed as collisions with physics calculating etc.

Resources