Sorry for my bad English.
I do a little game in JavaScript using Box2D (although I think the language is not important, because the engine is the same, as is well known, and has been exported to JavaScript).
Connecting several bodies via Distance Joint. When creating a joint pointing frequencyHz = 11 and dampingRatio = 0 (as I understand it, the less dampingRatio, the faster the item returns to its original position, that is, the spring will be tougher that I need). For each body to use force:
body.ApplyForce(new b2Vec2(0, 5800), body.GetWorldCenter())
That I needed to have these bodies was greater gravity than others.
After creating several elements, they begin to twitch, to vibrate as if they were something haunted, stop and engage in a certain position.
I tried to "play" with parameters frequencyHz and dampingRatio have joint, and sought to design not twitch, but then the construction seems less harsh and smoother.
There is some sort of solution?
Thanks.
I think that the structure is vibrating due to the fact that the weight of several elements, and the power applicable to them, the object is pulled down by increasing the length of the joint, the joint is aimed szhimatsya back to its original position, due to this vibration is obtained, because the element moves quickly in different directions
Related
I am using Matter.js physics in an attempt to create soft bodies. I was able to create a body like this:
However I am not sure if this is the "soft body" I want. It is true that this body is not entirely rigid and has that bouncy feel when it collides and gets dragged. I was looking for a body that shares similarities with a gelly. This image might visually help explaining the concept:
I was wondering how these type of bodies can be made. Is it the same as the as matter.js soft body but with a very specific type of properties? I can only get the body to be kind of rigid-squared and not as moldable and circular as I would like it to be.
I am also interesting in manipulating the physics body with in-game interactions which would increase or decrease the physics body size which leads me once more to the conclusion that the type of body that I want must be quite moldable.
Can matter.js handle this or do I have to change the physics engine? Any solutions to approach this?
NOTE: I am using Phaser.js for some in-game components but matter.js physics for physics manipulation because I believe Phaser integrated Physics can't simulate this type of complex body.
Thanks
EDIT: It is very similar to this Box2d :roll soft body ball. I just need to do that with a js engine I guess. Is there any?
As I mentioned in the comments, I am not familiar with phaser or how you would actually implement this within a Javascript framework. My goal here is maybe to give you some ideas on different ways to proceed, so hopefully you'll find this answer useful.
I will try to answer this:
I was wondering how these type of bodies can be made. ... I can only get the body to be kind of rigid-squared and not as moldable and circular as I would like it to be.
It is not necessarily clear what you want given this sentence. As I noted in comments, what I think you are looking for is plasticity, and I will describe a way which you could possible "cheat" that look with somewhat simple tools.
At the moment you describe the motion of your body by "It is true that this body is not entirely rigid and has that bouncy feel when it collides and gets dragged.". Currently your model works as such:
A point is connected to all other points as given in your mesh.
Every time step, a force is calculated between each pair. The total force on a joint (or point) is the sum of all these pair wise forces.
Each joint is associated with a part of the body (i.e. it has some mass m) and you calculate its acceleration with acceleration = force/m. From there on we calculate velocity and finally position.
The most interesting part of the steps above is nr 2, as that will greatly influence the motion of the whole body. A very common way to implement it is as an elastic potential that for a certain distance between two points gives some force. Like so:
function elasticPotential(p1, p2) {
// Given two positions p1 and p2 we calculate a force between them
distance = sqrt(pow(p1.x - p2.x, 2) + pow(p1.y - p2.y, 2) + pow(p1.z - p2.z, 2));
force = force_given_distance(distance); // A popular choice here is for example a spring force
return force;
}
Now, you already have the function described above built in in your framework, so you don't have to implement it. The reason I'm describing this is because it is essential to understanding how we can create plasticity. The problem with the above is that nothing will retain deformation---the nature of the elastic potential is that it has some rest configuration (most likely your first configuration) and it will always try to get back to that shape. We want the shape to remember how it was mis-shaped. This is what plasticity is.
Simple plasticity
Note first here that the problem of plasticity is a big research topic and in many cases far from trivial. My idea is as follows: if the distance between two connected points are larger than some threshold, remesh the points in the current configuration. That is,
for each pair(p1, p2):
if distance(p1, p2) > threshold:
recalculate_connection(p1, p2)
As you can see this is a very simple model for plasticity, and most likely not physically correct. However, it should be possible to get interesting behaviours my playing with the remeshing together with what elastic potential you choose.
If you provide me with more details I might be able to discuss the problem further, but right now I feel this answer is already longer than it should be.
TL;DR:
Create a "moldable" shape by remeshing your body during deformation. It might be tricky to get an exact desired physical behaviour, but it should be possible to create something that looks "gelly-like".
I'm doing voice recording in javascript, and storing the recording as an array of signed floats. What would I need to determine (and ultimately, adjust) pitch on the array? I've seen various algorithms for C++, but they don't seem to be very helpful in my situation. I even downloaded and tried this one to see if I could convert parts of it to javascript:
http://voicerecorder.codeplex.com/SourceControl/latest
But all that actually did was make the recording louder, regardless of the settings I chose.
I'm not going to try to provide an exhaustive answer here, but rather describe my own findings discovered on my journey of wrestling with similar issues in audio programming.
Pitch Detection
If you're sound is monophonic (as it sounds that is is based on your comment to jeff), I've implemented pitch detection using auto-correlation techniques, mostly because it's relatively simple compared to other pitch detection algorithms.
The idea, if you're unfamiliar, is as follows:
Slide a sample over itself (with a predetermined window size; in 1-sample increments)
At each step, calculate the absolute difference between the original wave and the slid window (hard to explain verbally).
as you slide the window, keep a record of the score calculated in (2)
when the wave correlates with itself, the score will hit a minimum, and the time-location of this minimum specifies the signals periodicity.
In my implementation, this was the only algorithm that worked well (when fed samples of my voice; I didn't try a variety of samples however).
That was a crude explanation of how autocorrelation works, and this article provides a very nice comparison of different pitch-detection algorithms:
https://ccrma.stanford.edu/~pdelac/154/m154paper.htm
Pitch Shifting
Of course, you could get really cheap pitch shifting by just resampling, but that sounds similar to a record being played too fast, which is not acceptable in many circumstances.
As far as pitch shifting goes, I haven't gotten that far yet in my implementation, but last I left off, I was looking at phase vocoders as a possible solution. What's hard is finding a decent explanation of how these algorithms work that provides some intuition on the reason why they work the way they do instead of just providing soley abstract mathmatical equations.
I'm trying to make a little platform game with pure HTML5 and JavaScript. No frameworks.
So in order to make my character jump on top of enemies and floors/walls etc., it needs some proper collision detection algorithms.
Since I'm not usually into doing this. I really have no clue on how to approach the problem.
Should I do a re-check in every frame (it runs in 30 FPS) for all obstacles in the Canvas and see if it collides with my player, or is there a better and faster way to do so?
I even thought of making dynamic maps. So the width, height, x- and y coordinates of the obstacle are stored in an object. Would that make it faster to check if it's colliding with the player?
1. Should I re-check in every frame (it runs on 30 FPS)?
Who says it runs in 30 FPS? I found no such thing in the HTML5 specification. Closest you'll get to have anything to say about the framerate at all is to programmatically call setInterval or the newish, more preferred, requestAnimationFrame function.
However, back to the story. You should always look for collisions as much as you can. Usually, writing games on other platforms where one have a greater ability to measure CPU load, this could be one of those things you might find favorable to scale back some if the CPU has a hard time to follow suit. In JavaScript though, you're out of luck trying to implement advanced solutions like this one.
I don't think there's a shortcut here. The computer has no way of knowing what collided, how, when- and where, if you don't make that computation yourself. And yes, this is usually, if not at all times even, done just before each new frame is painted.
2. A dynamic map?
If by "map" you mean an array-like object or multidimensional array that maps coordinates to objects, then the short answer has to be no. But please do have an array of all objects on the scene. The width, height and coordinates of the object should be stored in variables in the object. Leaking these things would quickly become a burden; rendering the code complex and introduce bugs (please see separation of concerns and cohesion).
Do note that I just said "array of all objects on the scene" =) There is a subtle but most important point in this quote:
Whenever you walk through objects to determine their position and whether they have collided with someone or not. Also have a look at your viewport boundaries and determine whether the object are still "on the scene" or not. For instance, if you have a space craft simulator of some kind and a star just passed the player's viewport from one side to the other and then of the screen, and there is no way for the star to return and become visible again, then there is no reason for the star to be left behind in the system any more. He should be deleted and removed. He should definitely not be stored in an array and become part of a future collision detection with the player's avatar! Such things could dramatically slow down your game.
Bonus: Collision quick tips
Divide the screen into parts. There is no reason for you to look for a collision between two objects if one of them are on left side of the screen, and the other one is on the right side. You could split up the screen into more logical units than just left and right too.
Always strive to have a cheap computation made first. We kind of already did that in the last tip. But even if you now know that two objects just might be in collision with each other, draw two logical squares around your objects. For instance, say you have two 2D airplanes, then there is no reason for you to first look if some part of their wings collide. Draw a square around each airplane, effectively capturing their largest width and their largest height. If these two squares do not overlap, then just like in the last tip, you know they cannot be in collision with each other. But, if your first-phase cheap computation hinted that they might be in collision, pass those two airplanes to another more expensive computation to really look into the matter a bit more.
I am still working on something i wanted to make lots of divs and make them act on physics. I will share somethings that weren't obvious to me at first.
Detect collisions in data first. I was reading the x and y of boxes on screen then checking against other divs. After a week it occurred to me how stupid this was. I mean first i would assign a new value to div, then read it from div. Accessing divs is expensive. Think dom as a rendering stage.
Use webworkers if possible easy.
Use canvas if possible.
And if possible make elements carry a list of elements they should be checked against for collision.(this would be helpful in only certain cases).
I learned that interactive collisions are way more expensive. Because you have to check for changes in environment while in normal interaction you simulate what is going to happen in future, and therefore your animation would be more fluid and more cpu available.
i made something very very early stage just for fun: http://www.lastnoob.com/
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.
I am creating a platform game in JavaScript using canvas which is entirely tile-based. What is the best method of storing the blocks of items in the game (walls, floors, items)? The thing is every tile can be destroyed or created.
Currently I have a 2D array so I am able to quickly check if an item is at a specific X & Y position. The problem with this is when the user moves and the map needs to scroll, I need to reassign every block. And what happens when the item is at x = 0? I can't use negative indexes.
I would rather the scrolling analogue as aposed to a tile at a time. Also I plan on randomly generating maps as the user moves and if it hasn't previously been generated. So once something is generated, it should stay that way forever.
Another point I should mention is that it will also be multiplayer. So chunking the screen is a great idea until the cached data becomes dirty and needs to get the latest from the database. Gah I'm so new to all this; seems impossible, any help is greatly appreciated.
Since you have infinite levels I'd suggest a structure similar to what you already have, with a slight tweak.
Instead of storing everything in one big array, and moving stuff around inside that array every time the user moves (ouch) instead store 9 chunks of map (each one a size such that it's roughly twice the size of the screen), when the user approaches the edge of the current chunk, dispose the chunks which are offscreen, move all the chunks left, and load new ones into the gap.
Hopefully that was clear, but just in case, here's a diagram:
The lettered squares are the chunks of map, and the red square is the viewport (I drew it slightly too large, remember the viewport is smaller than the black squares). As the viewport moves right, you unload chunks A B and C, move all the others left, and load new data into the right most ones. Since a chunk is twice the width of the screen, you have the time it takes the user to cross the screen to generate/load the level into those chunks. If the user moves around the world fast, you can have a 4x4 set of chunks for extra buffering.
To address the returning to previous chunks of map. there are a couple of ways to do that:
Write out the chunks to hard disk when they're no longer in use (or whatever the equivalent would be in javascript)
Expand your chunk set infinitely in memory. Rather than an array of chunks have an assosciative array which takes x/y position of the chunk, and returns the chunk (or null, which indicates that the user has never been here before and you need to generate it).
Procedurally generate your levels, that's complex but means that once a chunk goes off screen you can just dispose it, and be confident you can regenerate exactly the same chunk again later
There are obviously lots of ways to do this.
If they levels aren't too large, you can keep your original design of a 2d array and use a variable to store the current x/y scroll position. This means that you store all of the map information in memory at all times, and only access the parts you need to display on the screen.
When painting you work out which tile is visible at current scroll position x/y, how many tiles fit on the screen with the current screen width and only paint the ones you need.
If you scroll whole tiles at a time, then its pretty easy. If its a more analog scrolling, you will need some finer grain control of where in the tile you start drawing, or you can cheat and draw the whole set of tiles to an in memory bitmap and then blit that to the drawing canvas with an negative offset.
I once defined this very thing in XML and JSON... I think the JSON serialization would be alot faster and more efficient (not to mention easy) to work with in JavaScript, especially since JSON lends itself so well to variable length lists as you would require for "N" levels in each game.
Using a standard format would also make it more reusable and (ideally) encourage more collaboration (if that's what you're looking for). You can check out my first attempt to create a Video Game schema for level structure.
As fileoffset says, there are many ways to do it, but I highly suggest keeping your level data (i.e. concepts) separate from your rendering (i.e. objects in motion, paths, speed, timing, x/y/z co-ordinate positioning, etc...).
Again, as the article said that area is the most quickly changing, and there's no telling if WebGL, SMIL+SVG, Canvas+Javascript, good ol' Flash/Actionscript or something else will be the best route for you, depending on your needs and the type of game you are developing.