Touch controll problem

Hey,

I have a script, which works fine with the mouse:

if (Input.GetMouseButton(0))
{
	var ray : Ray = Camera.main.ScreenPointToRay (Input.mousePosition);
	var hit : RaycastHit;

	if (Physics.Raycast (ray, hit))
	{
		position.x = hit.point.x;
		position.y = 0;
		position.z = hit.point.z;
	}

	var direction : Vector3;
	direction.x = position.x - this.transform.position.x;
	direction.z = position.z - this.transform.position.z;

	rigidbody.velocity += Vector3(direction.x * speed * Time.deltaTime, 0, direction.z * speed * Time.deltaTime);
}

I have tried to translate it for touch controlls:

if (Input.touches.Length > 0)
{
	if (Input.touches[0].phase != TouchPhase.Canceled || Input.touches[0].phase != TouchPhase.Ended)
	{
		var ray : Ray = Camera.main.ScreenPointToRay (Input.touches[0].position);
		var hit : RaycastHit;

		if (Physics.Raycast (ray, hit))
		{
			position.x = hit.point.x;
			position.y = 0;
			position.z = hit.point.z;
		}

		var direction : Vector3;
		direction.x = position.x - this.transform.position.x;
		direction.z = position.z - this.transform.position.z;

		rigidbody.velocity += Vector3(direction.x * speed * Time.deltaTime, 0, direction.z * speed * Time.deltaTime);
	}
}

However, it doesn’t do anything. What is wrong with the code?

Thanks,
Akos

if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Began)

use this line for your if condition rather than

if (Input.touches[0].phase != TouchPhase.Canceled || Input.touches[0].phase != TouchPhase.Ended)

it will work

I guess you are running in Play Window (Emulator), which won’t generate touch events. (Maybe i’m wrong, but so far i can only test touch actions on devices :slight_smile:

y.tao