粒子在错误的地方繁殖



我正在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);
}
}

井而不是

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));
}
}
}
}
}

如果你点击屏幕来砍树,你可以在"命中";对象是,但是,如果您尝试实例化粒子来代替命中的对象,它将是树的原点,因此,您可以将树的碰撞器添加到树的表面,并使其成为不同的对象(也可以使其成为子对象(。所以这种方法不是很光滑,但你可以用这种方法在树的表面创建粒子。

同样,如果你用角色来切割它,你可以添加对撞机,它可以启用onTrigger到树上,当你触发时,你会在触发对象所在的地方产生一个粒子。

最新更新