Regarding touch position co-ordinate

hello friends, i am new in unity and i want to store touch position coordinate into a vector2 type variable. i am using this code..

if ( Input.touchCount == 1 )
{
        for(var touch :Touch = Input.touches[0]) 
        {
            if(Input.GetTouch(0).phase == TouchPhase.Began)
              var InitialP: Vector2=touch.position;

            if(Input.GetTouch(0).phase == TouchPhase.Moved)
              var FinalP: Vector2=touch.position;
        }
}

But it is showing error regarding the variable type conversion. so please help me as soon as possible.. thanks..

1 Answer

1

Couple things look suspicious

for(var touch :Touch = Input.touches[0])

I think you want to remove the [0], because Input.touches is an array, and you want to process each 'touch' in it.

var InitialP: Vector2=touch.position; (and the other one)

You've declared a variable in the body of a condition. I'm not 100% sure about JScript, but it might be that the scope of that variable (where it is valid) is only in that one line of code. You might want to declare those outside:

var InitialP: Vector2 = Vector2.zero;
var FinalP: Vector2 = Vector2.zero;

if ( Input.touchCount == 1 )
{
        for(var touch :Touch = Input.touches) 
        {
            if(Input.GetTouch(0).phase == TouchPhase.Began)
              InitialP =touch.position;

            if(Input.GetTouch(0).phase == TouchPhase.Moved)
              FinalP =touch.position;
        }
}