首页 > 解决方案 > 如何检测精灵是否与任何背景精灵重叠?

问题描述

当马对象越过矩形的边缘时,我想旋转马和马车。我想检测一个空的游戏对象是否在我绘制的精灵和相机之间。

背景对象被标记为“背景”并且位于“背景”层中。

目前,Debug.log 语句总是说“不检测背景”。我尝试了几次将光线投射的方向从后切换到前,但这并没有解决问题。射出射线的游戏对象的 z 位置为 -1,精灵的 z 位置为 0。精灵上有一个 2D 盒子碰撞器。

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

public class RoomMaker : MonoBehaviour
{
    public float speed = 5;
    public float distance = 5;

    public Transform horse;
    public Transform carriage;


    void Update()
    {
        transform.Translate(Vector2.right * speed * Time.deltaTime);

        RaycastHit2D backgroundInfo = Physics2D.Raycast(horse.position, Vector3.forward, distance);
        if (backgroundInfo)
        {
            Debug.Log("DETECTSBACKGROUND");

        }
        else
        {
            Debug.Log("Does not detect Background"); 
            //it always displays this one, it never displays the other debug.log

        }

    }
}

标签: c#unity3d

解决方案


考虑使用Physics2D.OverlapPointAll代替光线投射。

这将要求背景精灵Collider2D在其游戏对象上具有组件,它们的游戏对象被标记Background并位于background图层上。

我建议让background图层忽略与所有内容的冲突。有关如何执行此操作的更多信息,请参阅物理 2d 选项文档。

下面是代码的样子:

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

public class RoomMaker : MonoBehaviour
{
    public float speed = 5;
    public float distance = 5;

    public Transform horse;
    public Transform carriage;


    void FixedUpdate() // otherwise, visual lag can make for inconsistent collision checking.
    {
        transform.Translate(Vector2.right * speed * Time.deltaTime);

        Collider2D[] cols = Physics2D.OverlapPointAll(
                Vector3.Scale(new Vector3(1,1,0), horse.position), // background at z=0 
                LayerMask.GetMask("background")); // ignore non background layer objects


        Collider2D backgroundCol = null;
        for (int i = 0 ; i < cols.Length ; i++) // order of increasing z value
        {
            if (cols[i].tag == "Background") // may be redundant with layer mask
            {
                backgroundCol = cols[i];
                break;
            }
        }


        if (backgroundCol != null)
        {
            Debug.Log("DETECTSBACKGROUND: " + backgroundCol.name);

        }
        else
        {
            Debug.Log("Does not detect Background");     
        }

    }
}

我用这个设置进行了测试:

测试设置


推荐阅读