Strange touch behavior?
I have some code below and I cannot seem to work out where I am going wrong. Have spent the good part of two weeks testing many different combinations and I am starting to pull out when little hair I have left. Any help much appreciated.
I am trying to reliably spawn a prefab and get it to track under a finger position and when finger removed the prefab is destroyed. To do this I setup a prefab with a script that has a finger ID set when Instantiated. This ID is used to track the specific finger. Its also used to destroy the prefab if the same ID is matched with the fingerIDActive array.
Main Game Script
#pragma strict
var fingerPointPrefab : GameObject;
static var maxTouches : int = 11;
static var touchPos : Vector2[];
static var fingerIDActive : int[];
private var touchPhase : TouchPhase[];
function Start()
{
touchPos = new Vector2[ maxTouches ];
touchPhase = new TouchPhase[ maxTouches ];
fingerIDActive = new int[ maxTouches ];
}
function Update () {
var count = Input.touchCount;
for ( var i : int = 0;i < count; i++) {
var touch : Touch = Input.GetTouch( i );
var figID = touch.fingerId;
// Cache touch data.
touchPos[ figID ] = touch.position;
touchPhase[ figID ] = touch.phase;
// End finger marker
if (touchPhase[ figID ] == TouchPhase.Ended){
fingerIDActive[ figID ] = 0;
}
// Spawn finger marker
if ((touchPhase[ figID ] == TouchPhase.Began) && (fingerIDActive[ figID ] == 0)){
Instantiate(fingerPointPrefab, touch.position, Quaternion.identity);
fingerPointPrefab.GetComponent(JSFingerTracker).finderNumber = figID;
var PFname: String = ("FingerID" + figID);
fingerPointPrefab.name = PFname;
fingerIDActive[ figID ] = 1;
}
}
}
Prefab Script
#pragma strict
var finderNumber : int = 0;
private var fingerPos: Vector3;
private var worldPos: Vector3;
function Update () {
fingerPos = JSGameControler.touchPos[ finderNumber ];
fingerPos.z = 10;
worldPos = Camera.main.ScreenToWorldPoint(fingerPos);
transform.position = worldPos;
if (JSGameControler.fingerIDActive[finderNumber] == 0) {
Destroy(gameObject);
}
}
Expected behavior:
Should create a prefab under finger, track finger when moved and if finger removed the prefab should be destroyed.
Observed behavior: (When compiled on iPad1)
Prefabs are not spawned or destroyed reliably.
Many times when an additional finger is added, the previous finger placed gets its prefab spawned correctly under it.
And this is the strangest behavior and does not seem to happen 100% but it seems the more fingers you place down the more you get random jittering. This seems to get worse when fingers are placed in a line horizontally on the iPad when held in landscape mode. This gets so bad that they pop all over the screen appearing and disappearing randomly. Have even seen it spawning phantom finger points. Maybe my iPad is possessed!! lol
Note, I am fairly new to JavaScript and still have much to learn.