我如何修改这段代码来检测由3个或更多蓝色立方体组成的列(Unity)

问题描述 投票:0回答:1

所以我目前有这段代码,它检测一行立方体是否有 3 个或更多彼此相邻的红色立方体。立方体将占据的游戏区域为 5 个立方体宽,10-15 个立方体高。原因是因为我将对立方体进行编程,使其从游戏区域的顶部掉落,类似于俄罗斯方块。这就是为什么我使用的代码从一个从左到右的空游戏对象投射一条光线,另一个从右到左投射的空游戏对象被非红色的立方体阻挡。代码适用于水平检查,因为只有 5 个立方体需要检查。如果我使用相同的方法检查列,我发现由于列大约有 10-15 个立方体高,因此可能存在 3 个或更多蓝色立方体,其中来自顶部和底部的光线都被非蓝色立方体阻挡.

private void CheckHorizontalMatches(string color)
    {
        RaycastHit2D hit = Physics2D.Raycast(transform.position, rayDirection, Mathf.Infinity, cubeLayer);
        Debug.DrawRay(transform.position, rayDirection * 5f, Color.green); // Draw a green ray to visualize direction

        GameObject startCube = null;
        int count = 0;

        while (hit.collider != null && hit.collider.tag == color && !detectedRedCubes.Contains(hit.collider.gameObject))
        {
            Debug.Log("Obj Name:" + hit.collider.gameObject);
            count++;
            startCube = hit.collider.gameObject;

            // Check if the collided cube is not "Red" tagged, and if so, break out of the loop
            if (hit.collider.tag != "Red")
            {
                break;
            }

            startCube.layer = LayerMask.NameToLayer("detectedRedCubesLayer");
            detectedRedCubes.Add(startCube); // Add the cube to the list of detected cubes
            hit = Physics2D.Raycast(startCube.transform.position, Vector2.right, Mathf.Infinity, cubeLayer & ~(1 << detectedRedCubesLayer)); // Exclude the "detectedRedCubesLayer"
        }

        if (count >= 3 && detectedRedCubes.Count >= 3)
        {
            
        }
    }

注意:红色块只能水平“匹配”,蓝色块只能垂直“匹配”

到目前为止,我对代码的水平位感到满意,它检测是否有 3 个或更多红色立方体,因为最多只能有 5 个红色立方体可以排成一行。真正的问题是检测 3 个或更多彼此堆叠的蓝色立方体。

c# unity-game-engine
1个回答
0
投票

我认为你可以使用

Physics2D.RaycastAll
从上到下发射射线并检测任何类型的立方体。返回的数组也是按照从上到下的顺序排列的。如果只想检测顶部有多少个堆叠的蓝色立方体,则只需逐个检查每个立方体并数到有一个红色立方体即可。像这样的东西:

var hits = Physics2D.RaycastAll(transform.position, rayDirection, Mathf.Infinity, cubeLayer);
int count = 0;
for( ; count < hits.Length; count++)
{
    if(hits[count].collider.Tag != "Blue")
        break;
}
    
© www.soinside.com 2019 - 2024. All rights reserved.