Greetings,
I would like to move a gui texture, such as a crosshair, using iPhone´s accelerometer. Is it possible? Can anybody point me a direction?
Greetings,
I would like to move a gui texture, such as a crosshair, using iPhone´s accelerometer. Is it possible? Can anybody point me a direction?
There’s Input.acceleration which you can use to read the device’s accelerometer data (I’m not exactly sure whether orientation and gravity count as accelertion or not), and you can use it in the OnGUI function and move the crosshair in whichever way you want.
You should use Input.acceleration, doing something like this:
var crossHair: Transform; //drag the crosshair GUITexture from Hierarchy here var calH: float = 1.0; // you must tweak these calibration factors... var calV: float = 1.0; // to adjust the sensitivity in each direction private var acc: Vector3 = 0; function Update()( // smooths the acceleration input (it shakes a little due to electrical noise) acc = Vector3.Lerp(acc, Input.acceleration, Time.deltaTime); var posH = Mathf.Clamp(acc.x * calH + 0.5, 0, 1); // clamp values to... var posV = Mathf.Clamp(acc.z * calV + 0.5, 0, 1); // viewport coordinates crossHair.position = Vector3(posH, posV, 0); }
If the crosshair goes up/down when you tilt the device left/right, swap acc.x and acc.z in the two Mathf.Clamp lines above (only the arguments acc.x and acc.z, not the lines!). If the crosshair goes right when it should go left, change the sign of posH in the last line. The same applies to posV if the up/down direction is reversed.
EDITED: I’m assuming here that the y axis is perpendicular to the device screen. Based on the example shown in the docs, however, it seems z is perpendicular to the screen, y runs along the greater dimension and x runs along the device width. If this is the case, replace z by y in the above instructions.