How to detect collision between two objects in JavaScript with Three.js? - javascript

There a lot of nice things for collision detection like threex.colliders or code snippets here on questions, but acutally the most stuff is old (some functions like multiplyVector3 are changed and other are removed. I have a Object3D (Character Model) and a World (3D Models: cars, trees, buildings etc.). I can move the Character with the arrow keys (moving it via translateX/Y in a render loop.
What I want is a collision detection between the character model and everything else (except ground and some else). So I need a collision detection between Object3D (Character) and WorldObjects[] (all Objects).
So, now there are a few ways to get the wanted result maybe, which is the best (fast & readable) way to perform this? And now the problem (maybe) if it works: When the Character collides with anything else, how can I stop that he can move in this direction but he can go back, right or left?

You can detect collisions by using bounding boxes of objects. Bounding boxes are of type THREE.Box3 and have useful methods as isIntersectionBox, containsBox or containsPoint which will suit all your needs when you want to detect collisions.
Using them is as simple as this:
var firstObject = ...your first object...
var secondObject = ...your second object...
firstBB = new THREE.Box3().setFromObject(firstObject);
secondBB = new THREE.Box3().setFromObject(secondObject);
var collision = firstBB.intersectsBox(secondBB);
collision will be true if the boxes are colliding/hitting each-other.
This gives you an impression on how you can use bounding boxes.
You can also check this example out. I think it will be very useful for you.
EDIT:
You should maybe also checkout the Physijs library which is a plugin to three.js.
There is someone with a similar question on Stackoverflow that you might want to keep track of.

Related

How would I go about making a variable that allows me to toggle an object's visibility in Javascript

I am using the p5.js library to create Tetris. When someone gets a line clear (that is, a full line has been filled with Tetris blocks) then the tiles that made that line fill up should be removed/turned off.
What would be the best way to do this? For all visibility aspects of a tile, I use a show() function that draws a rectangle to show the tile. Should I add a variable to the object and check if that is true because executing the show function? Or is there a built-in method or function that makes removing an object easy? I can't seem to find anything like this online
It is hard to answer if we do not know how your tiles are represented in your program.
The method I recommend is to remove the tile from it's container structure altogether.
For example, if the state of your game is stored in a matrix, simply empty the cells that constitute a line. This way, your show() function should not be called at all.
Removing the tile from the container will work, but if its difficult then there is another way.
Have a variable to track whether the tile is being used and have its default be true e.g this.inPlay = true
Only update and show a tile if its inplay is true:
if (tile.inPlay == true) {
tile.update()
tile.show()
}
'''
If you want to remove it, just set its inplay to false
PS. a great tutorial for p5.js is on youtube (made by the coding train)
PPS. just search 'coding train p5.js tutorial' on youtube

Text with inset shadow three.js

I need to create text with inset shadow on my object in three.js, which looks like this:
Something like ring with engraved text.
I think the easier way to do that would be to use a normal-map for the engraving, at least if the text doesn't have to be dynamic (here's how you can export a normal-map from blender). And even if it needs to be dynamic it might be easier to create a normal-map dynamically in a canvas than to actually create a geometry for the engraving.
Another option would be to actually create a geometry that contains the engraving. For that you might want to look at the ThreeCSG-library, that let's you use boolean operators on geometries: You create the 3D-text mesh, warp and align it to the curvature of the ring and finally subtract it from the ring-mesh. This should give you the ring with the engraving spared out.
In fact, I was curious how this would actually work out and implemented something very similar here: https://usefulthink.github.io/three-text-warp-csg/ (source here).
In essence, This is using ThreeCSG to subtract a text-geometry from a cylinder-geometry like so:
const textBSP = new ThreeBSP(textGeometry);
const cylinderBSP = new ThreeBSP(cylinderGeometry);
const resultGeometry = cylinderBSP.subtract(textBSP).toGeometry();
scene.add(new THREE.Mesh(resultGeometry, new THREE.MeshStandardMaterial());
Turns out that the tessellation created by threeCSG really slow (I had to move it into a worker so the page doesn't freeze for almost 10 seconds). It doesn't look too good right now, as there is still a problem with the computed normals that i haven't figured out yet.
The third option would be to use a combination of displacement and normal-maps.
This would be a lot easier and faster in processing, but you would need to add a whole lot of vertices in order to have vertices available where you want an displacement to happen. Here is a small piece of code by mrdoob that can help you with creating the normal-map based on the displacement: http://mrdoob.com/lab/javascript/height2normal/

Conway's Game of Life - How to fake an "infinite" 2d plane

I'm using a 2d array to represent the grid of cells. When a cell on an edge or in a corner checks it's neighbors that would be out of bounds, it treats them as permanently dead.
function getCell(row, column) {
if(row === -1 || row === cellMatrix.length || column === -1 || column === cellMatrix[0].length)
{
return 0;
}
else return cellMatrixCopy[row][column];
}
I'd just like to get rid of behavior like gliders halting and turning into blocks when they reach the edge of the grid. How would you "get rid" of the edges of the array?
You can checkout the full implementation here. Thanks in advance.
How to fake an “infinite” 2d plane?
To create an infinite dimension game board use a sparse matrix representation where the row and column indicies are arbitrary-precision integers. Roughly as follows:
map<pair<BigInt,BigInt>, Cell> matrix;
Cell& get_cell(BigInt x, BigInt y)
{
return matrix[make_pair[x,y]];
}
The game of life is impossible to fake being infinite. Say the structure you create tries to expand past the current bounds, what is to stop it from expanding infinitely. Like MitchWheat said you could wrap the edges which is your best bet (for the more natural looking behavior), but since it's turing complete you can't fake it being infinite in every situation without having infinite memory.
Since the game of life is turing complete that means if a something "goes off the edge" it is impossible to tell if it will come back for a general case (related to the halting problem), meaning any heuristic you use to decide when something goes off the edge will have a degree of inaccuracy, if this is acceptable then you should consider that approach to, though IMO simulating the game of life incorrectly kinda defeats the purpose.
Another way to go would be to purposely simulate a larger area than you show so objects appear to go off the edge
This question is also here with some good answers.
The simplest modification to your simulation (and not mentioned on the other question) would be to triple the area's length and width, but only show what you currently show. The only catch would be if something went off-screen, hit the wall, and then came back. You could try playing around with the game rules at the boundary to make it more likely for a cell to die (so that a glider could get a little further in before becoming a block that could mess things up). Maybe that a live cell with three neighbors would die if it were within two steps of the side.
One of the other answers (and our answer) can be summarized as keeping track of the live nodes, not the entire screen. Then you would be able to do cool stuff like zoom and pan as if it were Google Maps.

HTML5 - Collisions [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I'm working on a top down game, and this game is going to contain a lot of collisions simple and complex.
After doing some research, I understand that I have to always compare my character with 'object' within my code - and then check for collision calculations.
EG:
CheckCollisions(Player, Object);
Which means I have to add in every single collide-able object within my scene, into my code:
CheckCollisions(Player, Building1);
CheckCollisions(Player, Building2);
CheckCollisions(Player, Trash);
CheckCollisions(Player, Bench1);
CheckCollisions(Player, Bench2);
CheckCollisions(Player, Office1);
CheckCollisions(Player, Office2);
First off, my objects might not even be simple rects, they might be complex shapes. Secondly, some of them might have their own rotation. And thirdly, what happens if I have over tens of thousands of collie-able objects in my scene?
Ins't there an easier way to check for collisions within a HTML5/JS game?
Is this even possible? I'm really just looking for some advice and pointers.
Thanks
It's very uncommon to have a named variable for every single object in your game. Usually you store all objects in one data structure (like an array) and when you need to do something with all objects, you do a for-loop over this array.
Some important objects, like the player character, could have an own variable, but they should also be in the "all objects" array, so you don't need to program a special handling to include the player character.
Regarding performance: When you check everything against everything, the amount of collision checks which need to be performed increases quadratically. But you can reduce the effort when you only check collisions of those objects which are already close to each other. Before you check collisions, you:
divide the playing field into rectangular zones (the zones must be at least as large as the largest object).
Then you assign each object to the zone its upper-left corner is in.
Then you take each zone, and check collisions of each object in it with the other objects in the zone and with all objects the three zones right, down and rightdown from it (for objects which overlap zone borders).
When you have very complex shapes, you could also speed up collision-detection by calculating a bounding-rectangle for each shape (the smallest possible rectangle it fits into). Before you check the collision between two objects, you first check if their bounding rectangles intersect. When they don't, there is no chance for the complex shapes to intersect, and you can skip all the complex calculations.
As everyone so far has indicated, an array of objects is much better than naming all your objects individually.
A much easier method of collision detection that might work for you is to have a central object that tracks all occupied spaces. For instance, let's call it LocationTracker for now.
Assuming you're only using x and y axes, you can have a Point object that stores an X and a Y location, (and if you want to get fancy, a timestamp). Each object as it moves would send an array of all the Points that it is occupying. For example, you can call locationTracker.occupySpace(player[i], array(point(3,4), point(4,4), point(5,4)), etc.
If your call to occupySpace returns false, none of the Points match and you're safe, if it returns true, then you have a collision.
The nice thing about doing it this way is if you have x amount of objects, instead of checking x*x times per move, you check x times max.
You wouldn't need to pass in all points of the objects, just the outer most ones.
1 - you don't need to write a line of code for every object in your game. Put them into an array and loop over the array:
var collidableObjects = [Building1, Building2, Trash, Bench1, Bench2,Office1, Office2];
var CheckAllCollisions = function() {
for (var i=0; i<collidableObjects.length; i++) {
CheckCollisions(Player, collidableObjects[i]);
}
}
2 - if you have complicated collision check (ie rotated shape, polygon, etc) you can first check a simple rectangle check (or radius check) and do the more accurate check if the first one returns true.
3 - if you plan to have tens of thousands of objects you should have smarter data collections, for example objects sorted by X coordinate so you can quickly avoid checking everything larger than Player.X+100 and smaller than Player.X-100 (using binary search), or split the objects into a grid and just check the objects in the 3x3 grid cells around the player.
A much better way is to put all your scene objects into an array or a tree structure and then
for( var i=0; i<scene.length; i++ ) {
scene[i].checkCollision( player );
}
if you add a function .checkCollision() to every object, you can handle any special case in there.
It's a good idea to make the player a rectangle so the checking code doesn't become too complex.
Make the collision-checking-rectangle of the player object slightly smaller than the actual sprite; that makes the life easier for your players.
First of all, you should always have your objects in arrays. This includes things like enemies, bullets and other such things. That way your game can create and destroy them at will.
You seem to be talking about the actual frequency of the collision checks, and not the collision check method. To that my advice would be to only run collision checks on a finite number of the objects. Try using a grid, and only checking for collisions with objects in the same grid block as the player.
Another thing that helps is to have plenty of "short cuts" inside the method itself. These are things that can be checked quickly and easily before any complex math is done. For example, you could check the distances between the two objects. If the objects are farther away than their farthest corner, you don't have to check for a collision.
There are plenty of these methods that you can utilize in your own unique combination.

Detecting collisions between two moving objects

I've got a basic Space Invaders type game going, and I can't get it to recognise when the shot from the player hits the alien. (I'm only checking Alien2 atm, the one second from the left). Since they're both moving, I've decided the only way to check for collisions is with either a range-based if statement (with 2 top coordinates and one left coordinate), or directly comparing the positions along the Y axis with Jquery.
I'm using the range-based solution at the moment, but so far it hasn't worked (not sure why).
My code so far:
if (key == "87"/*&& document.getElementById('BarrelOne').id=='BarrelOne'*/){
var Invader2 = document.getElementById('Alien2');
var Shot1 = document.getElementById('ShortShot');
Shot1.style.webkitAnimationPlayState="running";
setTimeout(function(){
Shot1.style.webkitAnimationPlayState="paused";
}, 1200);
if(document.elementFromPoint(625.5, 265.5) == Shot1){
Invader2.style.visibility="hidden";
}
};
Jsfiddle:
http://jsfiddle.net/ZJxgT/2/
I did something similar, and i found that it was much easier to achieve using gameQuery.
to test for collisions:
var collided = $("#div1").collision("#div2");
you can see full working example here
EDIT
If you're having trouble check out the API. For example, to find out how to use collisions check this part of the API.
the collision works in the following way:
This method returns the list of elements collisioning with the selected one but only those that match with the filter given as parameter. It takes two optional arguments (their order is not important). The filter is a string filtering element used to detect collision, it should contain all the elements the function should search collision into. For example if you look for collision with element of the class ‘foo’ that may be contained in a group you will use the filter ".group,.foo".
So, write something like this:
$("#ShortShot").collision("#Alien2").hide();
// will return the alien if it collides with ShortShot
or, to hide them both:
if (($("#ShortShot").collision("#Alien2")).length) {
$("#ShortShot").remove();
$("#Alien2").remove();
}
Instead of losing hours reinventing the wheel, I would suggest to switch (if still possible, depending on your time deadline) to a real 2D game engine for Javascript, with easy collision detection.
Check as well: 2D Engines for Javascript

Categories