I want to track the user’s movement along the Y axis and rotate an object relative to match (a lever).
What is the best method to achieve this? I have tried caching the initial position and calculating the angle between it and the ongoing hit position (but my trigonometry is lacking) so that did not work too well.
I would start with one of the camera control scripts from the wiki and modify it so it rotates a transform that you can assign in the Inspector.
I haven't written code to do this before, but I think you want something like this:
/* a variable to control the speed */
public var speedFactor : float = .002;
/* the transform you want to rotate */
public var someThing : Transform;
function LateUpdate ()
{
processTouchInput();
}
function processTouchInput ()
{
if ( ! someThing ) {
Debug.LogError("Thing is null");
return;
}
/* only rotate for one touch */
if ( Input.touchCount != 1 ) {
return;
}
var firstFinger : Touch = Input.GetTouch(0);
/* only deal with input if the finger has moved */
if ( firstFinger.phase != TouchPhase.Moved ) {
return;
}
/* get the current rotation of someThing's transform as a vector */
var theRotation : Vector3 = someThing.transform.rotation.eulerAngles;
/* calculate a change in rotation based on touch movement */
var movement : Vector2 = firstFinger.deltaPosition;
var deltaY : float = movement.y * speedFactor * Time.deltaTime;
/* adjust the y-coordinate of the rotation vector */
theRotation.y += deltaY;
/* set the rotation of someThing to the adjusted value */
someThing.transform.rotation = Quaternion.Euler(theRotation);
}
I may end up having to write something like this tonight to debug an issue I'm having...