I‘ve come across a situation / issue with collision handling, specifically with the function CollisionResponse() with my current class setup.
I'm kind of new to OOP in the way Playdate is recommending, I used to handle everything with tables in my previous ventures.
Say I have a class Machine that extends sprite, and in it I create a couple of sprites that make up the machine. I'm doing this so I can handle movement and collision of individual parts of the machine seperately (is this a valid approach?) One part of the machine, the hose, has a collider which should collide with other objects. Here is the example code:
class('Machine').extends(gfx.sprite) function Machine:init() Machine.super.init(self) self.x = 100 self.y = 100 --! Machine Body Sprite local machineBodyImage = gfx.image.new('example/machine-part1') self.machineBodySprite = gfx.sprite.new(machineBodyImage) self.machineBodySprite:moveTo(self.x,self.y) self.machineHoseSprite:setCollideRect( 0, 0, self.machineBodySprite:getSize() ) self.machineBodySprite:add() --! Machine Flexible Hose Sprite local machineHoseImage = gfx.image.new('example/example-head') self.machineHoseSprite = gfx.sprite.new(machineHoseImage) self.machineHoseSprite:moveTo(self.x+2,self.y+10) self.machineHoseSprite:setCollideRect( 0, 0, self.machineHoseSprite:getSize() ) self.machineHoseSprite:add() end function Machine:update() --! MOVEMENT self.machineHoseSprite:moveWithCollisions(self.x+2,self.y+10) --! COLLISIONS local collisions = self.machineHoseSprite:overlappingSprites() for i = 1, #collisions do local other = collisions[i] if (other:isa(Cargo)) then other:attach(self.machineHoseSprite) end end end function Machine:collisionResponse(other) if other:isa(Wall) then return 'freeze' elseif other:isa(Cargo) then return 'overlap' else return 'freeze' end end
Now the collisions with other objects work fine this way, but CollisionResponse() doesn't seem to get called at all. If I try to print anything inside of it (like other.classname), nothing shows up.
Is this because the collision happens with self.machineHoseSprite which is of type sprite, and CollisionResponse() only gets called for the parent class (Machine)? What would be a better way for handling this?
I'm thinking of situations where I want multiple colliders that act like triggers (with overlap) on my Machine object, and a main collider for freeze collisions as well. I thought I could just create individual sprites for this within the class, but as I said they don't seem to be picked up my CollisionResponse().
Thank you for your help.
Ah, I realised I can set the collisionResponse directly on my sprite:
self.craneHookBlockSprite.collisionResponse = 'slide'
I guess that works for simple things, but I would still need to find a way to actually use the callback so I can define different behaviour for different object types my sprite is colliding with.