Help with Raycast (85257)

Hi i’ve read many forums / answers about raycast but after many tests neither suits me.

I woul’d like to be able to draw a raycast from the center of the screen, directly to the center of the camera on the ground. I’ve tried this :

        Ray ray = new Ray(cam.position, cam.forward);
		RaycastHit hit;
		
		if(Physics.Raycast(ray.origin, ray.direction * 1000, out hit, 5f))
		{
			if(Input.GetButtonDown("Fire1"))
			{
				Destroy(hit.collider.gameObject);
			}
			Debug.DrawLine (cam.position, hit.point);
		}

Sorry for my bad english :wink:

Other than being too complicated, I don't see a probelm with your code. Ther are many other ways to do this task, but they should all give the same result. What is it doing that you don't want it to do? Note a simpler version that does the same thing: if (Physics.Raycast(ray, out hit, 5.0F) Note the * 1000 doesn't do anything. In addition, traditionally the Raycast would be inside the Input.GetbuttonDown() since the Raycast() fires every frame and the GetButtonDown() only fires for the single frame it is pressed.

I use the default first person character controller and when I 'see my foot' the raycast behaves strangely. It dishappears or it cuts. Thanks for the comment, i should invert Raycast() and Input.getButtonDown() thanks

You are likely hitting something you don't expect. Put the following as the first line in your raycast: Debug.Log(hit.colider.name+", "+hit.collider.tag);

Debug.Log(hit.collider.name+", "+hit.collider.tag); return First Person Controller, Untagged. The raycast hits the player controller ? Any way for ignore it ? Edit : I can use the "Layer mask" parameter right ?

1 Answer

1

when I ‘see my foot’ the raycast behaves strangely. It dishappears or it cuts.

Your ray starts from the cam position which is above the collider. When looking down, the ray hits the collider and then reports.

Now if you want to draw from a point to a point Linecast is more appropriate. Check layer to avoid hitting things you do not want to.

Raycast is for drawing from a point in a direction with distance (or not).

Yes thanks. Like robertbu said the ray hits the player collider. I've create a new Layer called "Player" and add it as paramater for the Raycast function. But now it's always return the player collider.. I can't use Linecast i don't now the end point.

You probably need to invert the layer layer = ~layer; And I see yes, no linecast here.

Thanks it works great ! Just why i need to invert the layer ?