gpt4 book ai didi

c# - Physics2D.OverlapCircleAll 未检测到其他游戏对象

转载 作者:行者123 更新时间:2023-12-01 21:55:03 26 4
gpt4 key购买 nike

我有一个敌人的预制件,它会在玩家周围的随机位置多次生成。然而,有时这会使一个敌人预制件与另一个敌人预制件重叠。

因此,我编写了一个脚本,该脚本使用 Physics2D.OverlapCircleAll() 在实例化敌人预制件之前检测所有碰撞器,从而避免敌人预制件与现有敌人重叠。我的问题是 OverlapCircleAll() 没有检测到预制件的其他实例。

我也已经尝试过使用 Physics2D.OverlapBoxAll。如果我生成超过 30 个这样的“敌人预制件”,至少有一个会与另一个敌人重叠

这是用于检测重叠的代码:

public void SpawnEachEnemy(GameObject Enemy)
{
Vector3 futurePosition = new Vector2(UnityEngine.Random.Range(UpperLeft.transform.position.x, DownRight.transform.position.x),
UnityEngine.Random.Range(UpperLeft.transform.position.y, DownRight.transform.position.y));
bool correctPosition = false;
while (!correctPosition)
{
Collider2D[] collider2Ds = Physics2D.OverlapCircleAll(futurePosition,0.2f);
if (collider2Ds.Length > 0)
{
//re-spawning to prevent overlap
futurePosition = new Vector2(UnityEngine.Random.Range(UpperLeft.transform.position.x, DownRight.transform.position.x),
UnityEngine.Random.Range(UpperLeft.transform.position.y, DownRight.transform.position.y));
}
else
{
correctPosition = true;
}
}

GameObject b = Instantiate(Enemy) as GameObject;
b.transform.position = futurePosition;
b.transform.parent = this.transform;
}

最佳答案

Louis Garczynski 提到了一些可能性,但没有提到的是,如果这些都在单个帧的跨度内实例化(基于评论说 SpawnEachEnemy 的猜测被称为在循环中),那么您可能需要在 Physics2D 设置 下启用Auto Sync Transforms:

Auto Sync Transforms enabled

minimal reproducible example当在新的 3D 项目场景中连接到相机时,在启用 Auto Sync Transforms 的情况下应该可以按照您的预期工作,并且在禁用时将无法防止重叠。这可能是阻止它为您工作的原因:

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

public class TestScript : MonoBehaviour
{
Vector3 upperLeft;
Vector3 downRight;

GameObject prefab;

// Start is called before the first frame update
void Start()
{
transform.position = new Vector3(0, 0, -3);
upperLeft = new Vector3(-1, -1);
downRight = new Vector3(1, 1);

prefab = GameObject.CreatePrimitive(PrimitiveType.Sphere);
DestroyImmediate(prefab.GetComponent<SphereCollider>());
prefab.transform.localScale = 0.4f * Vector3.one;
prefab.AddComponent<CircleCollider2D>();

for (int i = 0; i < 12; i++)
{
SpawnEachEnemy(prefab);
}

prefab.SetActive(false);

}


public void SpawnEachEnemy(GameObject Enemy)
{
Vector3 futurePosition;
Collider2D[] collider2Ds;

do {
futurePosition = new Vector2(
UnityEngine.Random.Range(
upperLeft.x,
downRight.x),

UnityEngine.Random.Range(
upperLeft.y,
downRight.y));

collider2Ds = Physics2D.OverlapCircleAll(futurePosition, 0.2f)
}
while (collider2Ds.Length > 0)

GameObject b = Instantiate(Enemy) as GameObject;
b.transform.position = futurePosition;
b.transform.parent = this.transform;
}
}

关于c# - Physics2D.OverlapCircleAll 未检测到其他游戏对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58175470/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com