Let’s say I have 5 different objects: Player- Player Bullet - Enemy1 - Enemy2 - Enemy Bullet
They all hit each other and I want to register that when it happens, I can use multiple if-else statements but that would get tedious especially with more objects being added:
if ((event.object1.id == “enemyBullet” and event.object2.id == “enemy1”) or (event.object1.id == “enemy1” and event.object2.id == “playerBullet”))
So, my question is, is there a more efficient way to test which object hit what. Also I would like to know the difference between : “event.object1, object2” and “event.target, event.other”
Thank you.
<<They all hit each other
Are you sure? Player’s own bullet hits player?? Enemy’s own bullet hits enemy??? If not, then as per other replies, step one is to implement filters to eliminate combinations you’ll NEVER care about.
>>is there a more efficient way to test which object hit what.
Assuming you still end up with a global collision listener, the “more efficient” way to implement these two-way if statements is to pre-sort your objects, quick pseudocode:
local obj1 = event.object1 -- aliases local oid1 = obj1.id local obj2 = event.object2 local oid2 = obj2.id if (oid1 \> oid2) then obj1,oid1,obj2,oid2 = obj2,oid2,obj1,oid1 -- swap-sort by id end
Having done that, you only now need to have “one-way” if statements, because obj1 is always the “lower” id, fe
if (oid1 == "enemy" and oid2 == "player") then -- (oid1=="player" and oid2=="enemy") need not be tested end
Having done that, restructure your if statements into “groups” by oid1
if (oid1 == PLAYER\_ID) then -- test here for all the oid2's than a player can collide with if (oid2 == ENEMY\_BULLET\_ID) then elseif (oid2 == POWERUP\_ID) then elseif (oid2 == MONEY\_ID) then end elseif (oid1 == ENEMY\_ID) then -- test here for all the oid2's than an enemy can collide with end
HTH