I want to send a raycast but not have it collide with my player.
How can I do this?
using UnityEngine;
using System.Collections;
public class ExampleClass : MonoBehaviour {
void Update() {
Vector3 fwd = transform.TransformDirection(Vector3.forward);
if (Physics.Raycast(transform.position, fwd, 10))
//hit something
}
}
But there is a way to ignore all trigger colliders. When we call Physics. Raycast, we can set the fifth parameter to QueryTriggerInteraction. Ignore.
Raycast which is specific to planes, Unity Raycasts hit colliders and nothing else. If you want an object to be hit by raycasts you need to add a collider.
add the following line to the Start() or Awake() method : gameObject. layer = LayerMask. NameToLayer ("Ignore Raycast");
As you can see, the raycast (red line) goes through the collider. Also the layer is correct. I also do a "debug" raycast which gives me all colliders hit on all layers. The result is that it hits the terrain (mesh collider) behind the collider, but not the desired collider in front of it.
I recently had this problem. It was a pain to figure out, yet it is a simple fix.
I found that if you go to Edit -> Project Settings -> Physics2d and Uncheck the box that says "Raycasts Start In Colliders" it solves this issue.
This makes it so that you do not have to deal with layers (I find layers to be a very impractical way of selectively raycasting). It just ignores the collider on the gameobject casting the ray, so you can have multiple prefabs of players/enemies casting rays and hitting each other, but not themselves.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With