-
Notifications
You must be signed in to change notification settings - Fork 2
Physics
Physics requires creating a PhysicsWorld object that is given to the rigidbody during construction. PhysicsWorld object is probably easiest to create inside scene initialization. By default the physics object presumes a timestep of 60 FPS(1/60). To change this provide your own PhysicsSettings to the constructor.
It is important to call physicsWorld.Update(dt) in your scene update to make physics work.
Physics collisions should be handled by using a PhysicsContactListener. PhysicsContactListener requires you to give it a function to handle collisions. e.g.
contactListener.onBeginContact = [](b2Contact* contact, GameObject* a, GameObject* b)
{
if(a->GetName() == "Enemy" && b->GetName() == "Player")
HurtPlayer();
};
physicsWorld.SetContactListener(&contactListener);To add physics to a GameObject you first need to either add a sprite or manually set it's size. After that just add a Rigidbody component to your gameobject.
gameObject.AddComponent(new Rigidbody(physicsWorld));You also need to call gameObject.Update(dt) in your scene update after the world update to update the position of the object(otherwise the gameobject wont move).
NOTE: You should not call transform functions on a GameObject that has a Rigidbody. This most likely will cause the collider and the visual representation to be out of sync. Rigidbody has it's own functions to move the object if required. You can also move the object to a starting position before attaching the Rigidbody component.
You can set a rigidbody as a trigger by calling SetTrigger on it.
You can filter collisions between physics object by using contact filtering.
The fastest and simplest way is to use groups. Groups work so that objects with the same positive group will always collide with each other and groups with the same negative group will never collide with each other.
// Rigidbody1 and 2 will never collide with each other
Rigidbody1.SetPhysicsGroup(-1);
Rigidbody2.SetPhysicsGroup(-1);A more powerful way to handle collison filtering is by using categories and masks(note that setting a group takes precedence over masks). You can set a category to a object and then a mask that states which categories to collide with(Category1 is the default).
Rigidbody1.SetPhysicsCategory(Category2);
Rigidbody2.SetPhysicsCategory(Category3);
Rigidbody3.SetPhysicsMask(Category2 | Category3);
// Rigidbody3 will now only collide with Rigidbody1 and 2Categories and masks fork through bitfields so that PhysObj1.Category & PhysObj2.Mask != 0.
Setting the mask to -1 (this is related to how negative numbers work in binary) will enable collison with everything and setting the category to 0 will disable collision with everything. You could also set the mask to ~Category1 which will enable collison with everything except Category1. Categories from 1 to 16 are available.