在某个位置实例化对象?

Instantiate Object at Certain Position?

首先我想说我...对此很陌生。希望这不是一个愚蠢的问题。我刚刚完成了一个脚本,它允许我砍倒一棵树,并在树消失后生成 3 块木头。我遇到的问题是,一旦原木产生,它们就会直立并堆叠在树的同一位置。

有没有办法让它们稍微散开并躺在树倒下的地方?

这是我的树脚本。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
public class TreeAi : MonoBehaviour
{
GameObject thisTree;
public int treeHealth = 35;
private bool isFallen = false;
public GameObject treeLog;
public GameObject treeLogOne;
public GameObject treeLogTwo;
public AudioClip treeFall;
private void Start()
{
thisTree = transform.gameObject;
}
void DeductPoints(int damageAmount)
{
treeHealth -= damageAmount;
}
void Update()
{
if (treeHealth <= 0 && isFallen == false)
{
Rigidbody rb = thisTree.AddComponent<Rigidbody>();
rb.isKinematic = false;
rb.useGravity = true;
rb.AddForce(Vector3.forward, ForceMode.Impulse);
StartCoroutine(destroyTree());
isFallen = true;
AudioSource.PlayClipAtPoint(treeFall, this.gameObject.transform.position);
}
}
private IEnumerator destroyTree()
{
yield return new WaitForSeconds(2.2f);
Destroy(thisTree);
Instantiate(treeLog, transform.position, transform.rotation);
Instantiate(treeLogOne, transform.position, transform.rotation);
Instantiate(treeLogTwo, transform.position, transform.rotation);
}
}

Instantiate() 的第二个参数是您希望放置对象的位置。在这种情况下,您使用的位置与树相同。

您需要稍微修改一下位置向量。 Unity 有一个 Random 方法,在这种情况下非常有用。

您可以像这样更新代码以使用此偏移量

// How far the random offset can stretch
var randomSpawnRadius = 2.0f;
// Take the current position and add a random offset times the radius
var treeLogOffset = transform.position += Random.insideUnitSphere * randomSpawnRadius;
Instantiate(treeLog, treeLogOffset , transform.rotation);
// Get another random position inside the radius
treeLogOffset = transform.position += Random.insideUnitSphere * randomSpawnRadius;
Instantiate(treeLogOne, treeLogOffset , transform.rotation);
treeLogOffset = transform.position += Random.insideUnitSphere * randomSpawnRadius;
Instantiate(treeLogTwo, treeLogOffset , transform.rotation);
}

另一种方法是将其设为函数,因为它相当重复

private void InstantiateAtRandomOffset(GameObject objectToInstantiate, Transform transform, float randomSpawnRadius)
{
  var itemOffset= transform.position += Random.insideUnitSphere * randomSpawnRadius;
  Instantiate(objectToInstantiate, itemOffset, transform.rotation);
}

然后您可以将代码中的调用替换为

InstantiateAtRandomOffset(treeLog, transform, 2.0f);
InstantiateAtRandomOffset(treeLogOne, transform, 2.0f);
InstantiateAtRandomOffset(treeLogTwo, transform, 2.0f);