Hey all,
I’ve been thinking about adding some simple portals to my game. And by “simple”, I mean the Super Meat Boy kind where an object that touches portal A is immediately and entirely moved to portal B-- as opposed to what I’d call “scary complicated wizardry” portals a seen in Portal where objects can exist half-way through each portal.
Anyways, the problem is that if an object touches portal A and is immediately moved to portal B, portal B will send it right back to A until Unity crashes. I haven’t done it, but I expect that would be the case. Also, I’ve read a couple of Unity Answers where people have tried to do this, encountered these results, and then received advice that wouldn’t work for me (like making the portals one-way, or offsetting the exit).
My first thought was that objects that can be teleported need to have a common interface so that they can be marked as “canTeleport = false” when entering and “canTeleport = true” when exiting (via OnTrigerExit2D). But that seems a little too hacky. I’m not completely against those kinds of solutions, but I’d like to find something better this time, if possible.
So the second idea was to give each portal a “canTeleport” property. When an object touches portal A, portal A would first do portalB.canTeleport = false, and then move the player. Portal B would be set to “canTeleport = true” again when the object triggers OnTriggerExit2D. There would need to be a few more things to handle to make sure that the object exiting portal B is the same one that was moved there from portal A, and also probably preventing portal A from teleporting anything else because if a second object exited portal B, the first object would be kicked back to A again. This is getting a little confusing. I hope I haven’t lost you. This solution seems like it could work, but it would be kind of limiting in that portals could be effectively closed as long as an object is in the way. I don’t really want that.
My final solution (yikes) was to make each portal system keep a list of objects that have passed through. OnTriggerEnter2D checks to see if the object is on the list. If it is, don’t teleport it. If it isn’t, add it to the list, then teleport it. OnTriggerExit2D finds the exiting object on the list and removes it. It would be possible for teleporting objects to be destroyed before they exit a portal, leaving a null pointer on the list. I was thinking that every x teleports, the teleporter system checks for nulls and removes them from the list.
What do you think? Particularly of my last idea there? I know it’s hard to say whether something is too expensive without knowing what my game is, but for all I know it’s “obviously” not a good idea. And, of course, if there are better ideas, I’m all ears.
Thanks for reading.
- Rob