【发布时间】:2020-01-03 20:23:27
【问题描述】:
让我先说我知道这是一个常见问题,但是我已经寻找解决方案并没有提出任何问题。
此代码适用于由榴弹发射器实例化的榴弹。期望的行为是手榴弹在地面上弹跳,但粘在玩家身上。 3 秒后手榴弹爆炸。
我正在使用transform.parent 让手榴弹粘在玩家身上。
using UnityEngine;
// Grenade shell, spawned in WeaponMaster script.
public class GrenadeLauncherGrenade : MonoBehaviour
{
#region Variables
public float speed;
public Rigidbody2D rb;
public GameObject explosion;
private int damage = 50;
private GameObject col;
#endregion
// When the grenade is created, fly forward + start timer
void Start()
{
rb.velocity = transform.right * speed;
Invoke("Explode", 3f);
}
// Explode
private void Explode()
{
Instantiate(explosion, gameObject.transform.position, Quaternion.identity);
try
{
if (col.tag == "Player")
{
Debug.Log("Hit a player");
col.GetComponent<PlayerHealth>().TakeDamage(damage);
}
}
catch (MissingReferenceException e)
{
Debug.Log("Could no longer find a player, they are probally dead: " + e);
}
Destroy(gameObject);
}
// Check if the shell hits something
private void OnCollisionEnter2D(Collision2D collision)
{
col = collision.gameObject;
if (col.tag == "Player")
{
gameObject.transform.parent = col.transform;
Debug.Log("Stick!");
}
}
}
更奇怪的是,在检查器中,手榴弹看起来像是父母,但它的行为却表明并非如此。我可以移动 TestPlayer,但手榴弹没有跟随。
【问题讨论】:
-
弹丸的检查器设置是什么?您可以将其添加为屏幕截图吗?
-
@HoloLady 确定,现在就这样做
标签: c# unity3d parent collision