Created
May 2, 2014 22:00
-
-
Save georgiee/7758583691d33a2c1af1 to your computer and use it in GitHub Desktop.
EntityContactListener
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class PinballGame.Core.CollideableEntity | |
constructor: (entity, shape)-> | |
@entity = entity | |
if shape instanceof Array | |
@shapes = shape | |
else | |
@shapes = [shape] | |
getCollisionShapes: -> @shapes | |
getEntity: -> @entity | |
hasShape: (givenShape) -> | |
if @shapes.length == 1 | |
return true if givenShape == @shapes[0] | |
else | |
for shape in @getCollisionShapes() | |
return true if givenShape == shape | |
return false | |
setPassThrough: (value) -> | |
@passthrough = value | |
for shape in @shapes | |
shape.passthrough = @passthrough | |
class PinballGame.Core.ContactCallback | |
constructor: (entity, enter, leave)-> | |
@entity = entity | |
@enterCallback = enter | |
@leaveCallback = leave | |
leave: (contact)-> @leaveCallback.call(undefined, @entity, contact) if @leaveCallback? | |
enter: (contact)-> @enterCallback.call(undefined, @entity, contact) if @enterCallback? | |
class PinballGame.Core.EntityContactListener | |
constructor: (game, entity)-> | |
@game = game | |
@entity = entity | |
@callbacks = [] | |
@game.physics.p2.world.on("beginContact", @onBeginContact) | |
@game.physics.p2.world.on("endContact", @onEndContact) | |
@game.physics.p2.world.on("preSolve", @onPresolve) | |
onPresolve: (presolve)-> | |
#console.log('onPreSolve', presolve) | |
if presolve.contactEquations.length > 0 | |
for ce in presolve.contactEquations | |
if (ce.shapeA.passthrough || ce.shapeB.passthrough || ce.bodyA.pseudoSensor || ce.bodyB.pseudoSensor) | |
ce.enabled = false | |
with: (entity, callbackEnter, callbackLeave) -> | |
shapes = entity.getCollisionShapes() | |
for shape in shapes | |
callback = new PinballGame.Core.ContactCallback(entity, callbackEnter, callbackLeave) | |
@callbacks[shape.id] = callback | |
onBeginContact: (contact) => | |
shape = @identifyOpposite(contact) | |
callback = @findCallbackForShape(shape) if shape? | |
#console.log 'onBeginContact', shape.id | |
callback.enter(contact) if callback? | |
onEndContact: (contact) => | |
shape = @identifyOpposite(contact) | |
callback = @findCallbackForShape(shape) if shape? | |
#console.log 'onEndContact', shape.id, callback | |
callback.leave(contact) if callback? | |
identifyOpposite: (contact)-> | |
return contact.shapeA if @entity.hasShape(contact.shapeB) | |
return contact.shapeB if @entity.hasShape(contact.shapeA) | |
findCallbackForShape: (shape)-> | |
return @callbacks[shape.id] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment