Why does this produce a bounce in box2d? - actionscript-3

I'm trying to get my box2d box to bounce when hitting another box2d box. The physical properties to both objects are set thus..
fixtureDef.density=1;
fixtureDef.friction=0;
fixtureDef.restitution=0.9;
And when I apply this line (which is meant to be the correct way of doing things) I get no bounce.
myElementsArray[0].myPhysics.myBody.ApplyImpulse(newVec, myElementsArray[0].myPhysics.myBody.GetWorldCenter());
But when I change the 2nd, part to some random vector, it bounces
myElementsArray[0].myPhysics.myBody.ApplyImpulse(newVec, new b2Vec2(20,20));
Which I don't get, what am I doing wrong?

The "bounce" you are seeing is probably a bit deceptive. I'm not a physics guru, I only know enough be dangerous as my main focus is game programming. Anyway here goes, the first statement uses the center of mass to apply the force to. When you are calculating a "bounce" using restitution, in most physics libraries it would very simply grab the largest restitution between the two collision objects:
restitution = Max( bodyA.restitution, bodyB.restitution )
Then disregarding torque, the new differential final velocities with respect to the restitution is:
–restitution * (bodyA.initialVelocity - bodyB.initialVelocity)
This is also more standardly written as:
–e(V1i - V2i)
Why is this important? Because this is probably the reason you are not seeing a bounce, the two initial velocities (without torque) are zeroing out. Now the second call to ApplyImpulse() uses a coordinate that is not the center of mass of the body. Because of this, Box2D is going to attempt to apply an angular velocity to the body. With that in mind a new series of equations will be used. I'm fairly confident that is where the problem resides, but someone else might correct me or know more about it.

Related

Sidescrolling Box2D Game

When creating Box2D sidescroller game, is it performance friendly to scroll through every object and move it (for example by x axis) as it does in the following code snap:
for(Body b: bodies) {
b.setTransform(-1, b.getPosition().y, b.getAngle());
}
I was also wondering about the rendering, if I render every texture on every body, I would be rendering the whole level at once and it would cost a lot of my precious FPS.
In contrast to the comments saying that this is a good way to do it, I don't think so.
It is not intuitive to move every entity in your world. When you run around through a forest in real life, the trees also don't move around you, but only you move.
Use an OrthographicCamera and change its position. When rendering via a SpriteBatch, draw all bodies exactly on the position where they are (probably with some METER_TO_PIXEL scaling factor) and use spriteBatch.setProjectionMatrix(camera.combined) on your SpriteBatch. This way only the visible bodies will be drawn automatically, since the camera transformation will get rid of all non-visible bodies.
And another hint: Try to avoid Body.setTransform(). Instead try setting linear velocity or apply forces/torque on the bodies. Using setTransform causes non-physical behaviour since it's basically like teleporting and might lead to weird effects and in my case sometimes even bugs.

libgdx box2d flip compound body

Hi I have a box2d compound body which is intended to be a vehicle seen in profile. when it goes backwards i'd like it to face the other way ie flip/reflect on the x axis. is there an easy way to so this? I find nothing in google though much false hits due to other uses of word reflection.
I could recreate the body but I'd have to do the whole out-of-time delete/add thing? and it seems a bit cumbersome. i tried body.getFixtureList and setting the vertices but tyhe method is flagged don't change the list. does that mean don't add remove? or don't edit? Anyways nothing changes on screen. Off to double-check my code...
Am I missing something?
Changing the vertices won't work. Only possibility to do that is to recreate the body as you said. And don't think that it will be slow just because you will have to delete it and then create it again. Box2d could probably create 100 of your vehicles in one frame without having too much of a struggle.
And for the whole flipping process you would scale your vertices x component by -1. And if your vertices origin wasn't in center of shape you would have to adjust the x coordinate of the whole vehicle (or just have the origin properly placed in the first place).
Also when recreating the body you would probably want to save the linear and angular velocity of your original body. And then once you create the new one apply those velocities to the new body. If you don't do that you would make your vehicle freeze once you do the flip.

Box2D AS3 - Refreshing the Shape or Hitbox?

I'm currently trying to implement a "crouch" function in my game. I'm using WCK with Box2D.
I have something rather basic, I generate my main character as an extension of a shape. This means that collision is automatically generated from the getgo. This is wonderful for a lot of things, but not everything.
I have a crouch/roll function. The problem is that the hitbox for crouching and standing are the same, so if a box drops onto you while crouching it "levitates" ontop of you since the hitbox is still the standing hitbox.
How would I go about "refreshing" the shape collision? Is there a way to delete the collision and make Box2D recalculate?
It's possible to filter contacts and prevent them from happening (using a contact listener or iterating the world's contact list) but I think there are better ways to do what you want.
You could split the body in two parts, and connect them with a prismatic joint (limits and motor enabled, collideConnected disabled). Standing up you'd have the motor push the parts apart to the upper limit and when crouching you'd pull them together to the lower limit thus reducing the height.
If you need really different shapes (e.g. a rectangle when standing and a circle for rolling around metroid style) this might work: Add both shape's fixtures to the body and use mask filtering to prevent the one you don't need from colliding with anything.

AS3 with Nape physics: How can I find a tangent from a point to a body?

The short question: Is there any simple way in Nape to calculate the points of tangency with a Nape body object or shape given a point outside that body?
What I'm trying to do is create Worms-style rope physics. It basically works as an extendable line/distance joint that automatically breaks into segments when it comes in contact with the level geometry. I do this by raycasting from the most recent pivot point; if there is a collision I offset from the collision point by a couple of pixels, create a new rope segment, and make that point the new pivot. In case my character is swinging around a sharp corner, I then recast from that point, looping as necessary, until I'm clear of the level geometry.
It works amazingly well given my lack of experience, but there's one little cosmetic glitch. The rope won't wrap "tightly" around a horn-shaped protrusion. It's pretty easy to see why this is happening. Refer to the figure below.
I cast a ray each time I step the Nape world at 60 frames/second. Figure 1 shows the difference between two example raycasts. The character (not pictured) is at the end of the line, and he's fallen past the cliff "edge" in relation to the pivot in one step, so the collision point falls short of the desired point of tangency.
Figure 2 is what I end up with. The wraparound logic still works, by offsetting from the surface and recasting, but it doesn't appear "taut."
What I want is something like Figure 3, which corrects the angle to find the actual point of tangency with the body and creates the new pivot from that.
My planned fallback is to offset the angle of the raycast by small increments and recast until I no longer strike the level geometry, then back up one and use that as the collision point. Even that will probably require fewer computations than "curving" around like in Figure 2, but I'm still wondering: is there an even simpler way?
Excuse me for not commenting, but I don't have needed points for that :)
I've used something similar before (not exactly the same) and I think the way to go is to save the points of each cast, get the one with highest difference from the starting point, based on the y axis (if the rope goes up, then you get the point with smallest y and vice versa (rope going down from starting point)).
Then you can fix the angle to point to this specific point, marked as an "edge". Later you can continue with the common pattern, as the rope will go in the other direction (exactly like the edge of a cliff).

Flash CS4 / AS3 symbol within symbols

I'm trying to create a multi-level dungeon adventure in Flash CS4. The layout is an instance created of a symbol called Level, within the symbol are multiple wall subsymbols (wall), instances of Wall. There is a collision routine to stop the player walking through the walls, called from Wall.As.
Level is drawn about the centre point (0,0).
When I create an instance on the stage of Level (level), the collision tester is using the xy coordinates for the walls drawn about 0,0, not the "real" xy where it's appearing on the stage.
So what I need to know, is how to "update" the xy for each wall subsymbol with the live stage information, overriding the XYs drawn in the parent. It has to be updated unfortunately (I can't keep it static), as the levels are big so have to scroll.
Thanks for your advice.
With all due respect forget your approach, you're reinventing the wheel for nothing and probably to end up getting worse performance. What you need is pixel-perfect collision detection and probably including basic physics so already we're talking a huge amount of work. If you want to build levels in a design way for a game, use this, it'll blow your mind how awesome/easy/cool this is:
http://www.gotoandlearn.com/play.php?id=135
Its always a guess when trying to answer questions like this, as there are a lot of unknowns. That being said, in programming, there are always more than a few ways to solve a problem. Examine your collision detection routine - if you worked with hitTestPoint, and the point that was being tested (mouseX,Y or your main actor) with localToGlobal, you likely wouldn't need to test for the x,y variables of your collision objects. Read up on those two subjects and this question might be rendered moot.
At any rate, you could update relative coordinates in your Wall.as instance by leveraging globlaToLocal:
public function get curLoc():Point
{
return globalToLocal(new Point(this.x, this.y));
}
and retrieve them from your parent class as a point you can then test against:
trace(_wall.curLoc);
Hope that helps
I suppose you could accomplish what you're trying to do by manipulating the transform property of the wall symbols, but honestly I would concur with Ascension Systems and just abandon your collision testing routine for something different.
You may not need to go all out with a physics engine for your game, in which case just use hitTestObject to do the collision detection.