如何检测数组中游戏对象重叠并调用指定方法时更新其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
CheckOverlapmethod completely ignores theo1ando2objects you pass to it. Instead, it loops through thespikeRightarray and checks each object's bounds against itself—which will always returntrue(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
CheckOverlapnow 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-whileloop ensures each spike keeps getting new random Y positions until it finds one that doesn't overlap with any other spike in thespikeRightarray. - 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
相关产品推荐
相关产品推荐

