Reputation: 1
i have 2 sprites that moving horizontly and i need them to fall down naturally ,when they hit a wall . i know how to do that in a simple way of changing position every frame, but this is not seems natural, and probably not the right way.
There is a way to discover the collision and then make them fall down, when thier speed and y axis is taking into consideration ?
i just couldnt find a simple way to do that with box2d or chipmunk .
any direction would be great. thanx.
Upvotes: 1
Views: 607
Reputation: 837
Firstly add a custom contact listener to your b2World.
public class Main
{
public function Main()
{
//init stuff
var cc:CustomContactListener = new CustomContactListener();
world.setContactListener(cc);
}
}
//then on hit call the hit function on sprite
public class CustomContactListener extends b2ContactListener
{
//Called when a contact point is added.
public override function Add(point:b2ContactPoint):void
{
//checks if the first shape is a sprite and second is a wall if true call Hit
if (point.shape1.GetBody().GetUserData().isSprite && point.shape2.GetBody().GetUserData().isWall)
{
point.shape1.GetBody().GetUserData().Hit();
}
else if (point.shape2.GetBody().GetUserData().isSprite && point.shape1.GetBody().GetUserData().isWall)
{
point.shape2.GetBody().GetUserData().Hit();
}
}
}
public class Sprite
{
public var hit:Boolean = false;
//Set hit to true and start applying realistic downward force
public function Hit()
{
hit = true;
}
//Enter frame event that applies force
public function step(e:Event)
{
if (hit)
{
b2Vec2 force = new b2Vec2(0, -9.8);
bodyOfSprite.ApplyLinearForce(force);
}
}
}
This relies on you setting the userdata of all the bodies you have as the class that holds it. i.e. Sprite, Wall. You could also do it the opposite way where you apply gravity all the time and also apply an opposing force. Then when you make contact with the wall you stop applying the other force and gravity takes effect.
Or like how @iforce2d puts it just check when the linearvelocity of the body of the sprite is close or equal to zero because that would indicate it has hit something that has stopped it, not just a wall though, then you can just set hit to true. And the step function will do the rest. This is limited though because it just needs it to slow down to trigger it not hit a wall which may not be desired.
Upvotes: 2
Reputation: 8262
If you are setting the velocity yourself, it's up to you to make it look natural :) Changing the vertical part of the velocity is not a good idea - just leave it how it was:
b2Vec2 vel = body->GetLinearVelocity();
vel.x = ...;
body->SetLinearVelocity( vel );
Upvotes: 0
Reputation: 24846
using any phys engine just set's the correct gravity in the world (b2World in case of box2D) and set the initial velocity of your body. So it will fall naturally
Upvotes: 0