Physics2D.Raycast layers argument not working

I have everything in my game on layer 0(default), and my player on User Layer 8.

I’m sending the raycast from within the player collider and it’s hitting the players own collider. If I start the raycast outside the collider it works fine. But this is so much extra work and the collider location could potentially change in perspective to where I need to cast from.

Here are some things I’ve tried, and all methods return hit.distance 0.

float distance = 1.5f;
        int castLayer = 1 << 8;
        castLayer = ~castLayer;
        int castLayer = 1 << 8;
        int castLayer = 8;
        int castLayer = 0;
//rayStart is the x/y of the player
hit = Physics2D.Raycast(rayStart, new Vector2(0, -1), distance, castLayer);

Every single article I read suggest I’m doing this right.

You can use an empty child object as a point to start your raycast from.

you need layermask to be NOT layer 8, which is
~(1<<8)

Or just turn the option off

1 Like

BoredMormon, that’s an interesting idea, but wouldn’t it still hit the colliders in the parent object?

hpjohn, the first code example where I’m setting the layermask is using ~(1<<8) and yet the raycast still hits. I could temporarily toggle the raycast start in colliders option but I would think raycast would work properly in the first place.

Okay, so I figured out the problem. User error of course. I wasn’t casting the ray far enough to hit anything so it was always returning a null value. I some reason thought I was casting it far enough. That however brings me to my next question, how do I tell distance in my game between objects? Is the only way to raycast? I don’t mean on the fly but as a general idea.

Not if its outside the parent colliders. Think just in front of a gun muzzle, or just below feet.

Vector3.Distance (transform.position, otherTransform.Position

Thanks, but I was aware of this already. I guess I was more so wondering if the Unity interface had a way of showing you distance such as a ruler like most photo editing tools. It would make a lot of sense to add such a feature if not.

To see distances in a scene its common to use a unit cube. You could build a distance ruler functionality relatively quickly.

1 Like

I made a measuring tool:

//Assets/Editor/QuickDistance.cs
using UnityEngine;
using UnityEditor;
using System.Collections;

public class QuickDistance : Editor {
    [MenuItem( "GameObject/Measure Distance Between 2 GOs" )]
    static void MeasureDistance () {
        Debug.Log( ( Selection.transforms[0].position - Selection.transforms[1].position ).magnitude + " Units between " + Selection.transforms[0].name  + " + " + Selection.transforms[1].name );
    }
    [MenuItem( "GameObject/Measure Distance Between 2 GOs", true )]
    static bool ValidateMeasureDistance () {
        return Selection.transforms.Length == 2;
    }
}

Put into Assets/Editor, select 2 GOs in the scene, and point to GameObjects-> Measure Distance

Ez

2 Likes