Touch and aim with a raycast line

Hello

I’m trying to fire a ray before my player shoots a ball in order to him/her aim at the object he wants to target.

I did first in my mac in order to understand it and it work with this script

    Ray ray = Camera.main.ScreenPointToRay(Input.);

	Debug.DrawRay (ray.origin, ray.direction * 100, Color.cyan);

	RaycastHit hit;

But then I did for my real game and has been no joy at all.

Here is the script I am using:

void Update () 
{
	if (Input.touches.Length <= 0) 
		
	{
		return;
	} 
	
	else // if there is a touch
		
	{
		//loop through all the touches on the screen 
		
		for(int i = 0 ; i < Input.touchCount; i++)
		{
			if (Input.touchCount > 0 && Input.GetTouch (0).phase == TouchPhase.Began)
				
			{
				Ray ray = Camera.main.ScreenPointToRay(Input.GetTouch(0).position);
				Plane plane = new Plane(Vector3.up, transform.position);
				float distance = 0;
				if (plane.Raycast(ray, out distance))
				{
					Vector3 pos = ray.GetPoint(distance);
					Debug.DrawRay (ray.origin, ray.direction * 100, Color.cyan);
					RaycastHit hit;
					
					if (Physics.Raycast (ray, out hit) == true) 
					{
						Debug.DrawRay(ray.origin, ray.direction * hit.distance, Color.red);
					}

But nothing really happens.

can some one help and telling me where is my mistake?

Thanks

CL

Debug.DrawRay() is documented as only working in the SceneView and GameView if you have gizmos. It is not intended to be a general-purpose line renderer, hence belonging to Debug class. Try:

for a general purpose line renderer.

I see two things with this code…

With this line:

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

… the code within this if statement will only work for one frame at best. You are saying “If there are some touches on the screen AND if my first touch is “beginning” a touch…” so this should only work on the first frame you put the first finger on the device. Is this what you intended?

The other is what Graham Dunnett pointed out, which is Debug.DrawRay is intended for editor use only as it is a debugging tool.

Additional suggestions could be to look at the Line Renderer class:

… and see if you can bend that to your will. There are also some 3rd party assets you can use like Vectrosity, but please do your research into 3rd party asssets, as I cannot endorse any of them.