Problems with raycasts and layers.

Hi everyone, I apologize if my question may sound trivial, but I need your help. I’m working on a project to recreate a remake of KulaWorld, an old game for PS1 where a ball rolls around and collects objects to complete the level. The ball can roll on cubes, even upside down. I’ve implemented a system using Raycasts, where if they hit the “ground” on Layer 8, it behaves in a certain way. Now, I want the Raycasts to detect invisible walls on Layer 10, so that the ball cannot pass through them. The problem is that the Raycasts are hitting objects on Layer 8 and not on Layer 10. Can someone help me?

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerMovement : MonoBehaviour
{
    public float speed;
    public RollingBall ball;
    public Animator ballAnim;

    private bool isMoving = false;

    private Vector3 rayFrontDirection;
    private Vector3 rayDownDirection;
    private Vector3 rayFrontDownDirection;

    private void Start()
    {
        recalculateRay();
    }


    private void Update()
    {
        if (Input.GetKey(KeyCode.Space))
        {
            JumpForward(2);
            if (Input.GetAxis("Vertical") > 0)
            {
                jumpAndMove(2);
            }
        }
        if (Input.GetKeyUp(KeyCode.Space))
        {
            StartCoroutine(smoothJump(2));
            AudioManager.Instance.PlayJumpSound();
        }
        if (Input.GetAxis("Vertical") > 0)
        {
            move();
        }
        else if (Input.GetKeyDown(KeyCode.A))
        {
            rotateLeft();
        }
        else if (Input.GetKeyDown(KeyCode.D))
        {
            rotateRight();
        }
    }
    void JumpForward(float offset)
    {
        StartCoroutine(smoothMoveAndJump(offset, 4));
    }
    void recalculateRay()
    {
        rayFrontDirection = transform.right;
        rayDownDirection = -transform.up;
        rayFrontDownDirection = transform.right - transform.up * 0.5f;
    }

    bool projectRay(Vector3 dir, float lenght = 3)
    {

        int layerMask = 1 << 8; // Layer 8: Muri, Layer 9: Player

        RaycastHit hit;
        Vector3 start = transform.position + transform.up / 2;

        if (Physics.Raycast(start, dir, out hit, lenght, layerMask))
        {
            Debug.DrawRay(start, dir * 1000, Color.red);
            Debug.Log("Il raycast ha colpito: " + hit.collider.gameObject.name);
            return true;
        }

        else
        {
            Debug.DrawRay(start, dir * 1000, Color.white);
            return false;
        }
    }

    GameObject getRayHit(Vector3 start, Vector3 dir, float lenght = 3)
    {
        int layerMask = (1 << 8) | (1 << 10);
        RaycastHit hit;

        if (Physics.Raycast(start, dir, out hit, lenght, layerMask))
        {
            Debug.DrawRay(start, dir * 1000, Color.red);
            return hit.collider.gameObject;
        }
        else
        {
            Debug.DrawRay(start, dir * 1000, Color.white);
            return null;
        }
    }

    IEnumerator smoothMove(float offset)
    {
        Vector3 targetPos = transform.position + transform.right * offset;
        while (Vector3.Distance(transform.position, targetPos) > 0.0001f)
        {
            float step = speed * Time.deltaTime;
            transform.position = Vector3.MoveTowards(transform.position, targetPos, step);
            ball.roll(-step * 100);
            yield return null;
        }
    }

    IEnumerator moveFront(float offset = 2)
    {
        if (isMoving)
        {
            yield break;
        }

        isMoving = true;
        yield return StartCoroutine(smoothMove(offset));
        isMoving = false;
    }

    IEnumerator moveUP()
    {
        if (isMoving)
        {
            yield break;
        }

        isMoving = true;
        yield return StartCoroutine(smoothMove(0.5f));
        Vector3 eulerUpAngle = new Vector3(0, 0, 90);
        yield return StartCoroutine(smoothRotation(eulerUpAngle));
        yield return StartCoroutine(smoothMove(0.5f));
        isMoving = false;
    }

    IEnumerator moveDown()
    {
        if (isMoving)
        {
            yield break;
        }

        isMoving = true;
        yield return StartCoroutine(smoothMove(1.5f));
        Vector3 eulerDownAngle = new Vector3(0, 0, -90);
        yield return StartCoroutine(smoothRotation(eulerDownAngle));
        yield return StartCoroutine(smoothMove(1.5f));
        isMoving = false;
    }
    void move()
    {
        recalculateRay();

        if (!projectRay(rayDownDirection, 1.5f))
        {
            return;
        }

        if (projectRay(rayFrontDirection, 1.5f))
        {
            StartCoroutine(moveUP());
        }
        else if (projectRay(rayFrontDownDirection))
        {
            StartCoroutine(moveFront());
        }
        else
        {
            StartCoroutine(moveDown());
        }
    }

    IEnumerator smoothRotation(Vector3 angle)
    {
        float duration = 10;

        for (int t = 0; t < duration; t++)
        {
            transform.Rotate(angle / duration);
            yield return null;
        }
    }

    IEnumerator rotateLeftsmooth()
    {
        if (isMoving)
        {
            yield break;
        }

        isMoving = true;
        yield return StartCoroutine(smoothRotation(new Vector3(0, -90, 0)));
        isMoving = false;
    }

    IEnumerator rotateRightsmooth()
    {
        if (isMoving)
        {
            yield break;
        }

        isMoving = true;
        yield return StartCoroutine(smoothRotation(new Vector3(0, 90, 0)));
        isMoving = false;
    }
    void rotateLeft()
    {
        StartCoroutine(rotateLeftsmooth());
    }

    void rotateRight()
    {
        StartCoroutine(rotateRightsmooth());
    }

    IEnumerator smoothJump(float offset)
    {
        if (isMoving)
        {
            yield break;
        }

        isMoving = true;

        Vector3 targetPos = transform.position + transform.up * offset;
        while (Vector3.Distance(transform.position, targetPos) > 0.0001f)
        {
            float step = speed * Time.deltaTime;
            transform.position = Vector3.MoveTowards(transform.position, targetPos, step);
            ball.roll(-step * 200);
            yield return null;
        }

        targetPos = transform.position - transform.up * offset;
        while (Vector3.Distance(transform.position, targetPos) > 0.0001f)
        {
            float step = speed * Time.deltaTime;
            transform.position = Vector3.MoveTowards(transform.position, targetPos, step);
            ball.roll(-step * 200);
            yield return null;
        }

        isMoving = false;

        ballAnim.Play("Jump", -1);
    }

    void Jump(float offset)
    {
        StartCoroutine(smoothJump(offset));
    }

    IEnumerator smoothMoveAndJump(float jumpOffset, float moveOffset)
    {
        if (isMoving)
        {
            yield break;
        }
        isMoving = true;

        recalculateRay();
        bool flyDown = false;

        if (projectRay(rayFrontDirection, 1))
        {
            moveOffset = 0;
        }
        else if (projectRay(rayFrontDirection, moveOffset))
        {
            moveOffset = moveOffset / 2;
        }

        Vector3 targetPos = transform.position + (transform.up * jumpOffset) + (transform.right * moveOffset);
        GameObject block = getRayHit(targetPos, rayDownDirection, 10);
        float landingOffset = jumpOffset;
        if (moveOffset != 0)
        {
            if (block != null)
            {
                float distance = Vector3.Distance(targetPos, block.transform.position) - 1.5f;
                distance = Mathf.Abs(distance);
                landingOffset = distance;
            }
            else
            {
                landingOffset = 10;
                flyDown = true;
            }
        }

        while (Vector3.Distance(transform.position, targetPos) > 0.00001f)
        {
            float step = 2 * speed * Time.deltaTime;
            transform.position = Vector3.MoveTowards(transform.position, targetPos, step);
            ball.roll(-step * 200);
            yield return null;
        }

        targetPos = transform.position - transform.up * landingOffset;
        while (Vector3.Distance(transform.position, targetPos) > 0.0001f)
        {
            float step = 2 * speed * Time.deltaTime;
            transform.position = Vector3.MoveTowards(transform.position, targetPos, step);
            ball.roll(-step * 200);
            yield return null;
        }

        ballAnim.Play("Jump", -1);

        if (flyDown)
        {
            Manager.Instance.InitDie();
        }

        isMoving = false;
    }

    void jumpAndMove(float offset)
    {
        StartCoroutine(smoothMoveAndJump(offset, offset * 2));
    }
}

Time to start debugging! Here is how you can begin your exciting new debugging adventures:

You must find a way to get the information you need in order to reason about what the problem is.

Once you understand what the problem is, you may begin to reason about a solution to the problem.

What is often happening in these cases is one of the following:

  • the code you think is executing is not actually executing at all
  • the code is executing far EARLIER or LATER than you think
  • the code is executing far LESS OFTEN than you think
  • the code is executing far MORE OFTEN than you think
  • the code is executing on another GameObject than you think it is
  • you’re getting an error or warning and you haven’t noticed it in the console window

To help gain more insight into your problem, I recommend liberally sprinkling Debug.Log() statements through your code to display information in realtime.

Doing this should help you answer these types of questions:

  • is this code even running? which parts are running? how often does it run? what order does it run in?
  • what are the names of the GameObjects or Components involved?
  • what are the values of the variables involved? Are they initialized? Are the values reasonable?
  • are you meeting ALL the requirements to receive callbacks such as triggers / colliders (review the documentation)

Knowing this information will help you reason about the behavior you are seeing.

You can also supply a second argument to Debug.Log() and when you click the message, it will highlight the object in scene, such as Debug.Log("Problem!",this);

If your problem would benefit from in-scene or in-game visualization, Debug.DrawRay() or Debug.DrawLine() can help you visualize things like rays (used in raycasting) or distances.

You can also call Debug.Break() to pause the Editor when certain interesting pieces of code run, and then study the scene manually, looking for all the parts, where they are, what scripts are on them, etc.

You can also call GameObject.CreatePrimitive() to emplace debug-marker-ish objects in the scene at runtime.

You could also just display various important quantities in UI Text elements to watch them change as you play the game.

Visit Google for how to see console output from builds. If you are running a mobile device you can also view the console output. Google for how on your particular mobile target, such as this answer or iOS: https://discussions.unity.com/t/700551 or this answer for Android: https://discussions.unity.com/t/699654

If you are working in VR, it might be useful to make your on onscreen log output, or integrate one from the asset store, so you can see what is happening as you operate your software.

Another useful approach is to temporarily strip out everything besides what is necessary to prove your issue. This can simplify and isolate compounding effects of other items in your scene or prefab.

Here’s an example of putting in a laser-focused Debug.Log() and how that can save you a TON of time wallowing around speculating what might be going wrong:

https://discussions.unity.com/t/839300/3

“When in doubt, print it out!™” - Kurt Dekker (and many others)

Note: the print() function is an alias for Debug.Log() provided by the MonoBehaviour class.

The difference between Layers vs LayerMasks:

https://discussions.unity.com/t/802897/2

“There are 10 types of people in this world: those who understand binary, and those who don’t.”

1 Like

You have 2 methods which perform raycasts. One is called projectRay the other is called getRayHit. The “projectRay” method only casts against layer 8 while your getRayHit will include layer 8 and 10. It seems your movement is only affected by the first method which does not cast against layer 10.

Your code is hard to follow, but if that’s your issue it would be kinde obvious :slight_smile:

2 Likes

Thank you so much! I had the solution right in front of my eyes, but I couldn’t see it. Thank you for your help.:slight_smile:

Thank you for responding and thank you especially for the explanation of Debug, which will definitely be useful to me in the future.