如何从碰撞中检查对象名称?

时间:2018-09-03 08:15:42

标签: c#

Example

我想将红色圆圈移动到仅与当前方形游戏对象碰撞的另一个框位置。

在我当前的代码中,例如单击某个游戏对象(正方形)之一。红色圆圈的位置将等于我单击的正方形的位置。我需要移动红色圆圈,只是邻居正方形。使用碰撞或其他样式,我该如何轻松地做到这一点?

1 个答案:

答案 0 :(得分:0)

enter image description here

enter image description here

实施:

public class StackOverflowScript : MonoBehaviour
{
    public Detector CircleObject;

    public SquareItem SquarePrefab;
    public Vector2 SpawnOffset;

    List<SquareItem> _squares = new List<SquareItem>();

    private void Start()
    {
        InitGrid();
    }

    public void InitGrid()
    {
        for (int i = 0; i < 6; i++)
        {
            for (int j = 0; j < 6; j++)
            {
                var pos = new Vector2(i, j) * SpawnOffset;
                SquareItem square = Instantiate(SquarePrefab, pos, Quaternion.identity) as SquareItem;
                square.Init(this, pos);
                _squares.Add(square);
            }
        }
    }

    public void MoveCircle(SquareItem item, Vector2 newPos)
    {
        if (CircleObject.Squares.Contains(item))
            CircleObject.MoveTowardPos(newPos);
    }
}

public class SquareItem : MonoBehaviour
{
    private StackOverflowScript _stackScript;

    public Vector2 Position
    {
        get; private set;
    }

    public void Init(StackOverflowScript script, Vector2 squarePosition)
    {
        _stackScript = script;
        Position = squarePosition;
    }


    private void OnMouseDown()
    {
        _stackScript.MoveCircle(this, this.transform.position);
    }
}

using System.Linq;

public class Detector : MonoBehaviour
{
    public List<SquareItem> Squares
    {
        get; private set;
    }

    public float DetectionRadius = 2f;

    void FixedUpdate()
    {
        Collider2D[] colliders = Physics2D.OverlapCircleAll(this.transform.position, DetectionRadius);

        Squares = colliders.ToList().FindAll(el => el.GetComponent<SquareItem>() != null).Select(el => el.GetComponent<SquareItem>()).ToList();
    }

    //This is for drawing the red circle in the inspector so you can control the radius of detection.
    private void OnDrawGizmos()
    {
        Gizmos.color = Color.red;
        Gizmos.DrawWireSphere(this.transform.position, DetectionRadius);
    }

    public void MoveTowardPos(Vector2 newPos)
    {
        this.transform.position = newPos;
    }
}

说明:

StackOverflowScript用于初始化正方形网格并控制圆的移动。

SquareItem是为您实例化的每个正方形附加的脚本,它包含现在的位置信息。

Detector是附加到您的圈子/玩家的脚本,如果邻居在一定半径范围内存在正方形,它将使用Physics2D重叠进行测试。

按下正方形项目时,它将其信息发送到stackoverflow脚本,后者负责检查正方形是否在圆的检测半径内。如果是这样,请将圆圈移到正方形位置。

希望这会有所帮助!

Execution Gif

干杯!