Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Raycast but ignore the collider of the gameobject it's being called from

Tags:

c#

unity3d

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            
    }
}
like image 718
user3795475 Avatar asked Jul 03 '14 20:07

user3795475


People also ask

How do you ignore colliders in raycast?

But there is a way to ignore all trigger colliders. When we call Physics. Raycast, we can set the fifth parameter to QueryTriggerInteraction. Ignore.

Can raycast hit object without collider?

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.

How do I make raycast ignore on gameObject?

add the following line to the Start() or Awake() method : gameObject. layer = LayerMask. NameToLayer ("Ignore Raycast");

Does raycast hit collider?

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.


1 Answers

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.

like image 110
Edge Developers Avatar answered Nov 12 '22 14:11

Edge Developers