Detecting Collisions
When two colliders collide with each other, the physics engine sends signals so your code can respond.
- BeforeCollide is triggered when a collider is begins contact with another collider.
- AfterCollide is triggered when a collider ends contact with another collider.
You would typically use an on block to listen for these events:
on BeforeCollide that {
if that.Category.Overlaps(Category.Unit) {
that.Health -= 10
}
}
Distinguishing Colliders
If a PolygonCollider was created with an Id parameter,
then normally it will send a signal to both
BeforeCollide and AfterCollide, as well as BeforeCollide<Id> and AfterCollide<Id>.
pub fn ship.Ship() {
use body=ship
Body(pos=@(0, 0))
PolygonCollider<hull>(shape=Isoceles(length=2, base=1), category=Category:Ship)
PolygonCollider<cockpit>(shape=Circle(radius=1), category=Category:Cockpit)
// Both these will be triggered when either the hull or cockpit begins/end contact with another collider
on BeforeCollide that {
Print { "Contact started" }
}
on AfterCollide that {
Print { "Contact ended" }
}
// These will be triggered only when the hull begins contact with another collider
on BeforeCollide<hull> that {
Print { "Hull contact started" }
}
on AfterCollide<hull> that {
Print { "Hull contact ended" }
}
// These will be triggered only when the cockpit begins contact with another collider
on BeforeCollide<cockpit> that {
Print { "Hull contact started" }
}
on AfterCollide<cockpit> that {
Print { "Hull contact ended" }
}
}
Collider Isolation
Sometimes you want to create a collider needs special handling that is separate from the usual collision handling.
The isolate=true parameter of PolygonCollider
can be used to make a collider only trigger the BeforeCollide<Id> and AfterCollide<Id> handlers,
and not the usual BeforeCollide and AfterCollide handlers,
allowing you to keep the handling of that collider separate from the handling of other colliders on the same entity.
pub fn ship.Ship() {
use body=ship
Body(pos=@(0, 0))
// ...
PolygonCollider<proximitySensor>(shape=Circle(radius=10), category=Category:Proximity, isSensor=true, isolate=true)
// These will not be triggered by the proximity sensor because it is isolated
on BeforeCollide that {
Print { "Contact started" }
}
on AfterCollide that {
Print { "Contact ended" }
}
// Both of these will be triggered when the proximity sensor begins/end contact with another collider
on BeforeCollide<proximitySensor> that {
Print { "Hull contact started" }
}
on AfterCollide<proximitySensor> that {
Print { "Hull contact ended" }
}
}