Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 13 Next capture
2021 2022 2023
1 capture
13 Jun 22 - 13 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
4
Question by oliver-jones · Apr 01, 2011 at 12:48 PM · collidertaglayermaskignore

Help With Ignoring Collider With Raycast!?

Hello,

I am using the FPS tutorial from Unity. I am using the machine gun script and I want to ignore a specific collider (Element 7 tag - want to ignore).

Here is the machine gun script, I've added the layerMask, but its still not ignoring the 7th tag which is on the collider I want to ignore?!? Any ideas?

function FireOneShot () { var direction = transform.TransformDirection(Vector3.forward); var hit : RaycastHit; var localOffset = transform.position + transform.up * 2; var layerMask = 1 << 7; layerMask = ~layerMask;

 // Did we hit anything?
 //transform.position + transform.up * 10
 if (Physics.Raycast (localOffset, direction, hit, range, layerMask) &amp;&amp; MachineGun == true) {
      Debug.DrawLine (localOffset, hit.point, Color.yellow);
     // Apply a force to the rigidbody we hit
     if (hit.rigidbody)
         hit.rigidbody.AddForceAtPosition(force * direction, hit.point);

     // Place the particle system for spawing out of place where we hit the surface!
     // And spawn a couple of particles
     if (hitParticles) {
         hitParticles.transform.position = hit.point;
         hitParticles.transform.rotation = Quaternion.FromToRotation(Vector3.up, hit.normal);
         hitParticles.Emit();
     }

     // Send a damage message to the hit object          
     hit.collider.SendMessageUpwards("ApplyDamage", damage, SendMessageOptions.DontRequireReceiver);
 }

 bulletsLeft--;

 // Register that we shot this frame,
 // so that the LateUpdate function enabled the muzzleflash renderer for one frame
 m_LastFrameShot = Time.frameCount;
 enabled = true;

 // Reload gun in reload Time        
 if (bulletsLeft == 0)
     Reload();           

}

Comment
Add comment
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

7 Replies

· Add your reply
  • Sort: 
avatar image
7
Best Answer

Answer by DcGoD · Apr 01, 2011 at 02:45 PM

If you want power over raycasting different layers you can selectively choose which layers are affected by the raycast. If you are only wanting to exclude one object then move that object to the ignore raycast layer such as the bottom of this post. Sometimes this may or may not work so knowing the proper technique WILL come in handy eventually.

link text

Casting Rays Selectively Using layers you can cast rays and ignore colliders in specific layers. For example you might want to cast a ray only against the player layer and ignore all other colliders.

The Physics.Raycast function takes a bitmask, where each bit determines if a layer will be ignored or not. If all bits in the layerMask are on, we will collide against all colliders. If the layerMask = 0, we will never find any collisions with the ray.

// bit shift the index of the layer to get a bit mask var layerMask = 1 << 8; // Does the ray intersect any objects which are in the player layer. if (Physics.Raycast (transform.position, Vector3.forward, Mathf.Infinity, layerMask)) print ("The ray hit the player"); In the real world you want to do the inverse of that however. We want to cast a ray against all colliders except those in the Player layer.

function Update () { // Bit shift the index of the layer (8) to get a bit mask var layerMask = 1 << 8; // This would cast rays only against colliders in layer 8. // But instead we want to collide against everything except layer 8. The ~ operator does this, it inverts a bitmask. layerMask = ~layerMask;

var hit : RaycastHit; // Does the ray intersect any objects excluding the player layer if (Physics.Raycast (transform.position, transform.TransformDirection (Vector3.forward), hit, Mathf.Infinity, layerMask)) { Debug.DrawRay (transform.position, transform.TransformDirection (Vector3.forward) * hit.distance, Color.yellow); print ("Did Hit"); } else { Debug.DrawRay (transform.position, transform.TransformDirection (Vector3.forward) *1000, Color.white); print ("Did not Hit"); } } strong text When you don't pass a layerMask to the Raycast function, it will only ignore colliders that use the IgnoreRaycast layer. This is the easiest way to ignore some colliders when casting a ray.

Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image
10

Answer by e-bonneville · Apr 01, 2011 at 12:54 PM

Just put the collider you'd like to ignore on the "IgnoreRaycast" layer.

Comment
Add comment · Show 1 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image
10

Answer by ajdrew81 · Aug 11, 2015 at 01:59 AM

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.

Comment
Add comment · Show 2 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image Riderfan · Nov 30, 2016 at 04:06 AM 1
Share

This only works in 2D.

avatar image Logophile · Aug 30, 2019 at 11:32 AM 0
Share

This is an awesome solution! Thanks a lot man!

avatar image
1

Answer by PsychoPsam · Apr 20, 2014 at 01:06 AM

I hope this helps someone. Here's my code to detect if the enemy can see the player (C#). Here's the settings - where the test object is the GameObject I'm looking for, and the Mask Layers String is an array of layers I want to ignore. If you want to add more layers to ignore increase the size of the array (i.e. to add another change 1 to 2 and there will be a space to add the name of another layer you want to ignore)

alt text

Make sure you add another C# script called LayerMaskExtensions to your found here too... link text using UnityEngine; using System.Collections;

 public class CheckViz : MonoBehaviour {
 
     public GameObject testObject;
     public string[] maskLayersString;
 
     LayerMask maskLayer; 
     // Use this for initialization
     void Start () {
         maskLayer = LayerMaskExtensions.Create("Ignore Raycast");
         foreach(string mask in maskLayersString)
         {
             maskLayer = maskLayer.AddToMask(mask);
         }
         Debug.Log(maskLayer.MaskToString());
         maskLayer = maskLayer.Inverse();
         Debug.Log(maskLayer.MaskToString());
     }
     
     // Update is called once per frame
     void Update () {
         // cast a ray to player
         // does the ray hit them first?
         Vector3 direction = testObject.transform.position - transform.position;
         RaycastHit2D hitInfo = Physics2D.Raycast(transform.position,direction,100,maskLayer);
         if(hitInfo.collider.gameObject == testObject)
         {
             Debug.Log( "I can see you!!!!" );
         }
         
     }
     void OnGUI()
     {
         Debug.DrawLine(transform.position, testObject.transform.position);
     }
 }



checkviz_settings.jpg (27.8 kB)
Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image
0

Answer by DerTeufel · Jun 20, 2013 at 08:14 AM

Short:

Raycast only 1 kind of object and ignore all others: Setup a new Layer e.g. User Layer 8.

 //Only raycast for layer 8
 LayerMask layerMask = 1 << 8;
 
 RayCast hit;
 
 //transform.position - the world koords where the raycast starts
 //transform.TransformDirection - the direction where the raycast should goto
 // out hit - the hit object
 // 2f - a float value equals the length of the raycast
 // layerMask - the layerMask, here ignoring all layers but 8
 
 Physics.Raycast(transform.position, transform.TransformDirection(Vector3.right), out hit, 2f,layerMask)


if you want to ignore only layer 8, it's the same code use

 LayerMask = ~1 << 8

instead

Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
  • 1
  • 2
  • ›

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

7 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

Appear and Dissapear: Fog 1 Answer

Tags returning true before collision 2 Answers

Network - Projectile, Prevent Collision with Parent 2 Answers

Why are raycasts so unreliable? 2 Answers

Ignore Collision after passing a collider 1 Answer


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges