You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何检测数组中游戏对象重叠并调用指定方法时更新其Y轴位置?

Fixing Overlap Detection & Position Randomization for Game Objects

Let's break down what's going wrong with your current code and fix it step by step to ensure your spikes don't overlap and update their positions correctly every time you call StartRandomizingRightSpikesPosition.

Issues in the Current Implementation

  • CheckOverlap Ignores Input Parameters: Right now, your CheckOverlap method completely ignores the o1 and o2 objects you pass to it. Instead, it loops through the spikeRight array and checks each object's bounds against itself—which will always return true (an object's bounds always intersect with itself). That's why your overlap detection isn't working as expected.
  • Incomplete Position Randomization: Your nested loop checks every pair of spikes twice (e.g., spike A vs B and B vs A), and after randomizing a spike's position, you don't re-check if it now overlaps with other spikes. This means you might still end up with overlapping spikes after the update.

Fixed Code Implementation

First, let's fix the overlap detection method to actually compare the two objects you pass in:

private bool CheckOverlap(GameObject o1, GameObject o2)
{
    // Get colliders for both objects (ensure they have Collider components attached!)
    Collider collider1 = o1.GetComponent<Collider>();
    Collider collider2 = o2.GetComponent<Collider>();
    
    // Only return true if both colliders exist and their bounds intersect
    return collider1 != null && collider2 != null && collider1.bounds.Intersects(collider2.bounds);
}

Next, update the position randomization method to guarantee non-overlapping positions and work efficiently:

public void StartRandomizingRightSpikesPosition()
{
    // Iterate over each spike in the array
    foreach (var spike in spikeRight)
    {
        bool isOverlapping;
        do
        {
            isOverlapping = false;
            
            // Generate a new random Y position
            float newYPosition = Random.Range(-7, 7);
            Vector3 originalPos = spike.transform.position;
            Vector3 candidatePosition = new Vector3(originalPos.x, newYPosition, originalPos.z);
            
            // Check if this candidate position overlaps with any other spike
            foreach (var otherSpike in spikeRight)
            {
                if (spike == otherSpike) continue; // Skip comparing a spike to itself
                
                // Temporarily set the spike to the candidate position to check overlap
                spike.transform.position = candidatePosition;
                
                if (CheckOverlap(spike, otherSpike))
                {
                    isOverlapping = true;
                    Debug.Log($"{spike.name} would overlap with {otherSpike.name} — trying new position");
                    break; // No need to check other spikes once an overlap is found
                }
            }
            
            // If no overlap, keep the candidate position; otherwise, loop again
            if (!isOverlapping)
            {
                spike.transform.position = candidatePosition;
            }
            
        } while (isOverlapping); // Repeat until we find a valid non-overlapping position
    }
}

Key Improvements Explained

  • Accurate Overlap Detection: The fixed CheckOverlap now uses the two input objects directly, includes null checks for colliders (to avoid runtime errors), and properly verifies if their bounds intersect.
  • Guaranteed Non-Overlapping Positions: The do-while loop ensures each spike keeps getting new random Y positions until it finds one that doesn't overlap with any other spike in the spikeRight array.
  • Efficient Checks: We skip self-comparisons and break early as soon as an overlap is detected, reducing unnecessary computations.
  • Clear Debugging: String interpolation in the log message makes it easy to see which spikes are causing overlap issues during testing.

内容的提问来源于stack exchange,提问作者Popa George

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 08:10:15