我正在 Unity 中制作一個游戲,您可以在其中砍伐樹木,我想讓它在您擊中樹的地方產生粒子。此時粒子在玩家所在的位置生成,這是因為腳本在玩家身上。但是我怎樣才能在正確的地方產生粒子呢?(我撞到樹的地方)它可能甚至沒有那么難解決,但我無法弄清楚。我當前的 C# 代碼如下。
public class ChopTree : MonoBehaviour
{
public int damage = 25;
public Camera FPSCamera;
public float hitRange = 2.5f;
private TreeScript Tree;
// Particles
public GameObject particles;
void Update()
{
Ray ray = FPSCamera.ScreenPointToRay(new Vector2(Screen.width / 2, Screen.height / 2));
RaycastHit hitInfo;
if(Input.GetKeyDown(KeyCode.Mouse0))
{
if(Physics.Raycast(ray, out hitInfo, hitRange))
{
// The tag must be set on an object like a tree
if(hitInfo.collider.tag == "Tree" && isEquipped == true)
{
Tree = hitInfo.collider.GetComponentInParent<TreeScript>();
StartCoroutine(DamageTree());
StartCoroutine(ParticleShow());
}
}
}
}
private IEnumerator DamageTree()
{
// After 0.3 seconds the tree will lose HP
yield return new WaitForSeconds(0.3f);
Tree.health -= damage;
}
private IEnumerator ParticleShow()
{
// After 0.3 second the particles show up
yield return new WaitForSeconds(0.3f);
Instantiate(particles, transform.position, transform.rotation);
}
}
uj5u.com熱心網友回復:
好吧,而不是
Instantiate(particles, transform.position, transform.rotation);
確保使用命中樹位置,例如
Instantiate(particles, Tree.transform.position, transform.rotation);
實際上,我個人會將兩個協程合并在一起并傳入相應的樹:
private IEnumerator ChopTree(TreeScript tree)
{
// After 0.3 seconds the tree will lose HP
yield return new WaitForSeconds(0.3f);
Instantiate(particles, tree.transform.position, transform.rotation);
tree.health -= damage;
}
然后
void Update()
{
var ray = FPSCamera.ScreenPointToRay(new Vector2(Screen.width / 2, Screen.height / 2));
if(Input.GetKeyDown(KeyCode.Mouse0))
{
if(Physics.Raycast(ray, out var hitInfo, hitRange))
{
// The tag must be set on an object like a tree
if(hitInfo.collider.CompareTag("Tree") && isEquipped)
{
var tree = hitInfo.collider.GetComponentInParent<TreeScript>();
if(tree)
{
StartCoroutine(ChopTree(tree));
}
}
}
}
}
uj5u.com熱心網友回復:
如果您通過單擊螢屏來砍樹,則可以在“命中”物件所在的位置生成它,但是,如果您嘗試實體化粒子代替命中物件,它將是樹的原點,因此,您可以將樹的對撞機添加到樹的表面并使其成為不同的物件(也可以將其設為子物件)。所以這種方式不是很平滑,但是您可以通過這種方式在樹的表面上創建粒子。
此外,如果你用字符切割它,你可以添加對樹啟用 onTrigger 的對撞機,當你觸發時,你會在觸發物件所在的位置生成一個粒子。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/436235.html
上一篇:如何通過按鈕上的腳本獲取子文本?
下一篇:UnityC#中普遍變化的音量