【问题标题】:Instantiate Object at Certain Position?在某个位置实例化对象?
【发布时间】:2020-06-22 17:53:28
【问题描述】:

首先我想说的是我……对此非常陌生。希望这不是一个愚蠢的问题。我刚刚完成了一个脚本,它允许我砍倒一棵树并在树消失后生成 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(treeLogTwo, transform.position, transform.rotation);”时transform.position 是生成片段的位置,将其更改为所需位置
  • 我明白了!现在是相对于树的位置吗?或者如果我改变它,它是否会基于地图上的其他地方?
  • 取决于你的目标是位置还是localPosition

标签: c# unity3d game-engine


【解决方案1】:

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

您需要稍微修改位置向量。 Unity 有一个 Random 方法,在这种情况下真的很有帮助。

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

// 随机偏移可以伸展多远
var randomSpawnRadius = 2.0f;
// 取当前位置并添加一个随机偏移乘以半径
var treeLogOffset = transform.position += Random.insideUnitSphere * randomSpawnRadius;
实例化(treeLog,treeLogOffset,transform.rotation);
// 获取半径内的另一个随机位置
treeLogOffset = transform.position += Random.insideUnitSphere * randomSpawnRadius;
实例化(treeLogOne,treeLogOffset,transform.rotation);
treeLogOffset = transform.position += Random.insideUnitSphere * randomSpawnRadius;
实例化(treeLogTwo,treeLogOffset,transform.rotation);
}

另一种方法是让它成为一个函数,因为它相当重复

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-18
    • 1970-01-01
    • 2017-09-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多