HT for Web visualization quadtree Four cross-tree collision detection

Source: Internet
Author: User

Quadtree Four fork Tree as the name implies is a tree-like data structure, each node has four children nodes, the two-dimensional plane can be recursively split sub-regions. Quadtree is often used for spatial database indexing, 3D of the vertebral visible region clipping, and even image analysis processing, we are introducing today is quadtree most often used in the game field of collision detection. The use of the Quadtree algorithm will greatly reduce the number of collisions that need to be tested, thus improving game refresh performance, this example is based on the HT for web graphics engine, sharing the same data model Datamodel through Graphview and Graph3dview, The 2D and 3D collision view effects are presented simultaneously under the Quadtree algorithm:

Quadtree implementation has a lot of mature version, I chose the https://github.com/timohausmann/quadtree-js/Four fork tree algorithm is very simple, so this open source library also Paraya line code. The use is also very simple, constructs a Quadtree object, the first parameter passes in the RECT information to develop the game space scope, in each requestanimationframe refreshes the frame, first clears the old data through the quadtree.clear (), Insert a new node rectangular area through Quadtree.insert (rect), so that Quadtree is initialized, and the rest is to call Quadtree.retrieve (rect) to get the specified rectangular region as needed. An array of rectangular objects that may intersect to be detected.

I built the HT Graphview and Graph3dview two components, Because two views share the same datamodel through Ht.widget.SplitView, the rest of our focus is only data operations on Datamodel, 200 Ht.node objects are built, and the attr attribute of each object holds the random motion direction of VX and VY, with When you save a rectangle object that will be repeatedly inserted into the Quadtree, the object is repeatedly created when each frame is updated, and the rectangle object references ht. Node object, which allows us to specify the HT associated with a rectangle object that needs to be detected when it is obtained through Quadtree.retrieve (rect). Node object, because we need to set the effect of the red color on the elements that are ultimately detected as collisions, which is HT. Node usually displays the default blue color, which will change to red when colliding with each other.

It is important to note that getting an array of rectangular objects from Quadtree.retrieve (rect) that needs to be detected will contain its own entities, and these are just elements that might collide, not that it has collided, because our example is a rectangle, so HT is used. Default.intersectsrect (R1, R2) determines whether the intersection is final, if your example is a circle, you can calculate whether the two center distance is less than two radius to determine if the intersection, so the final judging criteria depending on the game type will be different.

The use of quadtree or greatly improve the performance of the operation, otherwise 100 elements need to 100*100 the monitoring, I This example scenario is generally 100* (10~30) of the volume:

In addition to the collision detection Quadtree algorithm There are many interesting application areas, interested in playing this https://github.com/fogleman/Quads

All codes are provided below for reference:

functioninit () {d= 200; speed= 8; Datamodel=Newht.                                    Datamodel (); G3d=NewHt.graph3d.Graph3dView (Datamodel); G2d=NewHt.graph.GraphView (Datamodel); Mainsplit=NewHt.widget.SplitView (g3d, g2d);                                            Mainsplit.addtodom (); G2d.translate (300, 220); G2d.setzoom (0.8,true);  for(vari=0; i<100; i++) {        varnode =Newht.        Node (); NODE.S3 (Randminmax (5, Ten, Randminmax (5, 30)); NODE.P3 (Randminmax (-D/2, D/2), 0, Randminmax (-D/2, D/2)); NODE.S ({' Batch ': ' Group ',            ' Shape ': ' Rect ',            ' Shape.border.width ': 1,            ' Shape.border.color ': ' White ',            ' Wf.visible ':true,            ' Wf.color ': ' White '        }); Node.a ({Vx:randminmax (-Speed , speed), Vy:randminmax (-Speed ), obj: {width:node.getWidth (), Height:node.getHeight (),                            Data:node}});    Datamodel.add (node); } createshape ([{x:-D, y:d}, {x:d, y:d}, {x:d, y:-d}, {x:-D, Y:-d}, {x:-d, y:d}]); Quadtree=NewQuadtree ({x:-D, y:-D, Width:d, height:d});               Requestanimationframe (update);} functionUpdate () {quadtree.clear (); Datamodel.each (function(data) {if(! (Datainstanceofht. Shape)) {varPosition =data.getposition (); varVX = DATA.A (' VX '); varVY = data.a (' vy ')); varW = data.getwidth ()/2;varh = data.getheight ()/2;varx = position.x +VX; vary = position.y +VY; if(X-w <-d) {DATA.A (' VX ',-VX); X=-D +W; }            if(x + W >d) {DATA.A (' VX ',-VX); X= D-W; }            if(Y-h <-d) {DATA.A (' Vy ',-VY); Y=-D +h; }            if(y + H >d) {DATA.A (' Vy ',-VY); Y= D-h;                                    } data.setposition (x, y); varobj = data.a (' obj '); obj.x= X-W; Obj.y= y-h;            Quadtree.insert (obj);        SetColor (data, undefined);                    }    }); Datamodel.each (function(data) {if(! (Datainstanceofht. Shape)) {varobj = data.a (' obj '); varOBJS =Quadtree.retrieve (obj); if(Objs.length > 1){                                             for(vari=0; i<objs.length; i++ ) {                    varData2 =Objs[i].data; if(data = = =data2) {                        Continue; }                    if(HT. Default.intersectsrect (obj, data2.a (' obj '))) {setcolor (data,' Red '); SetColor (Data2,' Red ');    }                                                }                                         }        }    });                    Requestanimationframe (update); }                        functionrandminmax (min, max) {returnMin + (Math.random () * (Max-min));} functionCreateshape (points) {shape=Newht.    Shape ();    Shape.setpoints (points); Shape.setthickness (4); Shape.settall (10); SHAPE.S ({' All.color ': ' Red ',        ' Shape.background ':NULL,        ' Shape.border.width ': 2,        ' Shape.border.color ': ' Red '                        });     Datamodel.add (Shape); returnshape;}functionsetcolor (data, color) {DATA.S ({' All.color ': Color,' Shape.background ': Color});}

HT for Web visualization quadtree Four cross-tree collision detection

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.