Understand, use, and modify our one-way colliders.
You can download this tutorial and all the project files by getting Chipmunk2D for Unity on our store and download page.
Chipmunk2D demonstrates its powerful feature set by showing how simple creating one-way platforms can be. Creating a platform you can jump up through and then stand atop is often very difficult in engines like PhysX, because it's inherently un-physical. Common problems include getting stuck half-way, still hitting edges of platforms, being forced through the bottom like marbles sucked through jelly with a vacuum, etc.
One-way platforms are also an excellent introduction to the power of Chipmunk's collision callbacks. All the necessary code is here:
Place this code inside a ChipmunkCollisionManager class, and collision callback methods will be called automatically. Let's break down each part of this.
ChipmunkPreSolve_player_oneway deals with collisions between two collisionTypes, objects that are marked player and objects that are marked oneway. Collision types can be set in the inspector.
ChipmunkPreSolve means that this is a pre-solve callback. Pre-solve callbacks are called before the collision event is handled. Since one-way platforms cause collisions to be ignored, we want to figure that out before the physics engine processes the collision. In-depth details about the four collision handler types are in the Chipmunk2D Collision Handler docs.
arbiter.Ignore() tells the collision arbiter, the object that manages this specific collision, to ignore this collision between these two objects. This very simply and correctly handles all sorts of issues that could include getting stuck inside an object. To determine if this collision should be ignored, the collision normal is examined. Since the player is touching the bottom of the block, the collision normal should point downward; collision normals are unit length vectors that point out of the surface being struck. If the y value is less than -0.7, it means that vector is pointing mostly downward.
What's next? Extend this concept to make one-way doors going left or right by checking the x value of the normal. If player.HasKey(), allow them to move through certain doors. The very simple arbiter.Ignore() unlocks massive possibilities!
How is the quality and stability? Because collisions are not rejected on a frame-by-frame basis, but instead on a per-collision basis, we have complete stability. Check out the BasicOneway example scene, where we run a slow motion demonstration. If the sphere does not move above the platform and separate from it, it will pass through the platform without resistance. Velocity based functions ("Ignore this collision if the ball is moving upwards") are not this stable!