Multi-Touch Handling on Unity iPhone

There are a lot of questions on the Unity forums about how to handle multi-touch on iPhone. We’ve done a few experiments with multi-touch–although nothing in a game yet–but here’s one solution. This had a few goals:

  • Avoid iPhoneTouchPhase, which is unreliable (particularly with the remote)
  • Abstract touch tracking logic from game logic
  • Use a minimal amount of code


Multi-Touch Example (Unity iPhone) from Matthew Wegner on Vimeo.

This solution breaks the problem up into two classes, a Tracker and a Manager.  The core of the manager uses a Hashtable to tie tracker objects to their finger IDs.  The logic looks like:

  1. Reset all trackers to “clean” state
  2. Loop through all touch events
    1. If we don’t have a tracker for this finger ID, create one (and assume touch has started)
    2. If we already have a tracker object for this finger ID, tell it to update
    3. Mark tracker as dirty
  3. Any trackers that are still marked clean are assumed to be ended

There is some logic separation here, although it isn’t as clean as it could be.  The code that’s spawning/moving cubes is placed directly into the TouchTracker class.  In production we would strive to split this up, so the grunt work of tracking touches is totally separate from any game logic.  You could have your game logic get notifications of new/ended touches, or you could subclass TouchTracker and set up functions like OnTouchStarted, OnTouchEnded, and OnTouchUpdated.  Unity presents a lot of options for situations like this.

Enjoy the example, and comment if you make any changes or improvements.  This is far from perfect, but I think it’s a good direction to take.

Download Multi-Touch Sample Project

你可能感兴趣的:(iPhone)