I want to detect when the user in my ThreeJS is looking at one of the animation models. Currently I am using this code:
ourRaycaster.setFromCamera(g_Mouse, g_ThreeJsCamera);
g_AryObjectsLookedAt = ourRaycaster.intersectObjects(g_ThreeJsScene.children, true);
The problem is that although the raycaster will detect any collisions between the current camera line of sight and a child object in the animation models group, it will not intersect with any empty spaces in the group. Although this makes sense from a technical point of view, it doesn't match what we do as humans when looking at an object. When we look at an object, we mentally draw a shape around the overall object and if we are looking inside that pseudo-shape we feel that we are looking at the object.
For example, if you have a big head and wide shoulders, but a very thin neck, if I focus momentarily at the space alongside your neck I still feel that I am looking at "you".
What I need is a raycaster that when it passes through an animation model's group of children, does approximately the same thing.
Here is a concrete example. I am using the sample robot animation model from the ThreeJS examples. It has a really big head. When I do the raycast from this distance, no part of the robot is in the intersecting objects list:
But if I get right up "in its face", it is detected (it's "face" is detected):
This is technically accurate but I need something a lot more forgiving so I can create proper logic for interactions between animation model and the user. How can I do this without having to iterate manually with every animation model in the virtual scene?
Related
I am trying to building a HTML5 canvas game so that I will need to detect collision with character with different shape.
If you have enough knowledge about this type of collision please share your knowledge
Depends on personal preference.
One of them is Distance Detection.
Check the distance between two objects(or coords of said object), and if its close enough, count it as hit.
You could also check overlap this way, which is a definite hit. Then just apply whatever physics you wanted to apply.
The HTML Canvas is only in charge of displaying your "game" through a web browser. You'll need to utilize a bit of programming logic to decide what you want to render through the canvas. As far as the collision implementation, it'll depend on what you're looking to create.
We'll assume this is a 2d plane with objects moving in all directions.
Given this assumption, one implementation might be to attach positional coordinates to each object in your game, and consistently keep track of each object coordinate with a "global" game state. You can than perform calculations on each object's position and trigger collisions between objects that meet a certain threshold.
Implementation might differ depending on what you're looking to build but this link might be useful. Hope this helps!
The correct way is to go with a physics engine. Somethng like:
https://brm.io/matter-js/
However, it might be overkill for a simple game. here are the basics for collision detection.
You know the coordinates and size of all the objects you control.
After each movement, get the perimeter coordinates of each object. Each object will have an array of points marking its perimeter.
Compare the arrays and see if the same coordinate is present in two arrays.
This is the basic. You need a lot of enhancement to this code for a practical game. But you can figure them out after this step.
say you have a simple raycaster. When you mouse over, the model will light up.
However, in this implementation, this model would be broken into parts, which would be parts of the model but still their own separate "models". For example, say your model happened to be a car. When you mouse over the hood, it lights up. When you mouse over the door, it lights up, etc.
I did not find any such instance of what I was speaking of in the threejs examples.
is there a way to break a full .obj model into several, individual but connected, models in three.js?
I have been working with threejs for quite a time but I do not think that this is possible, at least not with threejs itself (maybe WebGL has some tools which would help you to achieve this, but still, if it is a complex model such as car, the result would still be pretty terrible). But there are several workarounds.
In treejs, create your model from multiple smaller ones. For simple objects this is possible (example: instead of sphere, create two hemispheres and place them next to each other).
Instead of using raycaster, use point light. This will cast the light on the area not the object, therefore if you target one big object, you will end up lighting up only the part of the object, based on the intensity and distance of the point light.
If you have complex model such as car. Load it with some 3D modelling program (Blender, ...) and break it into smaller ones and then save each of them separatelly. And in your threejs code, load each one separatelly and position them the way it will look like single object. (I guess this is the only reasonable way in this case)
I'm trying to simulate a rope physically correct on a website.
Having searched the web, my conclusion is that I need a physics engine like box2d?
If I have understood it right the solution is to split up an object into small segments and then to join and animate these all together. In addition, I want to combine the physics with the browser. What that means is: when I'm scrolling the website fast down, the rope has to react in a physically correct manner.
is this possible?
You don't need a library at all.
You can happily do this with object, component or procedural code, and an understanding of basic mechanical physics and some 2D geometry (basic calculus might help).
Doing it in an optimized fashion would require more work.
Doing it in a modular and reusable fashion would require some upfront engineering.
But making a rope, and making the rope behave normally is quite straightforward.
A 2D rope would be a series of line-segments or "bones".
Each bone can bend around its joints.
You can apply gravity or whatever other forces you would like to each bone.
Each bone has constraints (the other bones it's attached to, above and below).
So as you update the "rope", you update each bone, based on the constraints which came before and after.
You can create an anchor point -- pinning the top of the rope to the wall, so that regardless of how the other bones move, the top-most bone will pivot around its top joint, but will not move anywhere.
To apply physics to the middle of the hanging rope (like pulling it by the middle, and then letting go), you would use Inverse Kinematics to solve how that force against one or two joints affected each of the other attached (and constrained) joints.
Think of it less like a snake, and more like a bike chain.
The shorter each "link" in the chain, the more fluid the rope will seem, but the longer it will take to process.
The longer each "link" in the chain, the faster you can compute the changes, but the more rigid and blocky it seems as it bends.
Look up "Verlet Integration", "Kinematics" ("Forward"/"Inverse") and have a half-decent grasp of the math behind rotation and moving an object along 2D vectors...
With a little bit of mass in there, if you want to get fancy with the whip-like stuff, rather than just making waves.
The rest is just loops.
See the following for a basic example:
http://gamedev.tutsplus.com/tutorials/implementation/simulate-fabric-and-ragdolls-with-simple-verlet-integration/
And have fun.
If I have a canvas with a circle that changes color upon clicking on it, I can use a click event on the canvas element and handle the math for that (distance formula calculation <= radius). But what if I have two circles that overlap (like a van diagram), and I click in the middle of the two circles assuming that only the top circle should change color? If the math of the first circle is applied in this case, both circles would change color.
How would I deal with events in the canvas in terms of overlapping objects like the example above? With hopefully a fast/efficient algorithm?
You might want a framework like EaselJS that has a better api for what you're trying to do. Barebones canvas 2d-context doesn't provide much in terms of display-object / sprite behavior.
Responses above also mention some sort of list to represent layers. I don't think the implementation would be very difficult, just another condition to check for along with the radius.
Canvas isn't really like Flash or like a DOM tree whereby things have sort orders or z-indexes. Its a bit more like a flat rastered image and you have to rely upon other logic in your javascript to remember the sequence & stacking order of things you have drawn.
If you need this kind of interactivity I've always found it best to use a 3rd party library (unless it really is just a case of one or two circles which dont do much).
For interactive 'shape' based javascript graphics I would sugest Raphael.js or D3 which are actually more of SVG tools than a canvas one so maybe it's not for you but they are simple and cross-browser.
There's also processing.js (js port of Processing the Java lib) which feels a bit like flash and again can track all of the levels and objects. Theres a tonne of others but thats another topic.
If it's super simple the options might be:
Hold the co-ordinates of all shapes/elements composited on the canvas inside an object or array which also tracks their z-index/sort sequence, thereby letting you know whats on top.
Using the imagedata at the mouse coordinate of the click to establish what has been clicked
using multiple canvases composited on each other and letting the DOM do the work for the click events
Intent on creating a canvas-based game in javascript I stand before a choice:
Should I performance-wise keep all the stuff happening in the screen in one canvas (all the moving characters, sprites) and redraw it at constant rate of, say, 60 FPS or should I break the scene into several smaller canvases thus removing the need of redundant redrawing of the scene? I could even create separate canvas elements for the characters' limbs and then do most of the animation by simply manipulating the CSS of the given canvas element (rotation, positioning, opacity).
To me the latter sounds way more plausible and easier to implement, but is it also faster? Also, shouldn't I perhaps use SVG, keep the characters and sprites as elements inside of it and manipulate their XML and CSS properties directly?
So what do you think is the most fitting solution to a scene with severals sprites and characters:
One canvas object redrawn manually (and wastefully) at FPS rate
Several canvas elements, redrawn manually in a more reasonable fashion
Structured vector graphics document like SVG / VML manipulated via DOM
I am mainly concerned about the performance differences, but the legibility of the logical code behind is also of interest (I, having already worked with canvas before, am for example fairly sure that the redrawing function for the entire canvas would be one hard-to-maintain beast of a script).
DOM manipulations are slow in comparison to GPU-accelerated canvas operations, so I would stay away from SVG and VML.
As far as structuring your canvas code goes, it certainly doesn't make sense (especially for performance reasons) to clear and re-draw the entire canvas because the player moved or performed an action. Based on your description here, I'm guessing that your game will be 2D. These types of games lend themselves extremely well to layering unless you're doing something rather complex like Paper Mario. You should be looking at the issue from an object-oriented viewpoint and encapsulating your drawing procedures and objects together as appropriate.
For instance, create a player object that maintains a small canvas representing the character. All the logic needed to maintain the character's state is kept within the object and any changes made to it need not worry about other components of the game's visual representation. Likewise, do the same for the background, user interface, and anything else you can abstract into a layer (within reason). For example, if you're doing a parallax game, you might have a foreground, background, character, and user interface layer.
Ultimately you will need to maintain the state of the different components in your game individually. Player animations, background clouds moving, trees swaying, etc. will all be managed by appropriate objects. Since you will already have that type of code structure setup, it makes sense to just maintain major components on separate canvas elements and composite them together as needed for better performance. If the character moves in the bottom left corner of a scene with a static background, you don't need to re-draw the top right corner (or 95% of the scene, for that matter). If you're considering full-screen capabilities, this is definitely a performance concern.
There's a rule in programming, that you should never try and optimize something before you have a speed problem with it. You'll spend more time trying to figure out how to code something in the best way than to actually code, and will never finish anything.
Draw them all on your canvas at a fixed rate. That's how it's done. If you start creating a canvas for each limb and element and manipulate them using CSS, you're wasting the potential of canvas. Might as well just use images. That's how they did it before canvas. That's the problem canvas was made to solve.
If you ever encounter speed issues, then you can start hammering at them. Check out these slides for some tips (related video). This guy's blog also has some handy tips on canvas performance.