首页 > 解决方案 > 当子弹碰到他时玩家不会死

问题描述

图片

我的玩家在被我坦克的子弹击中时不会死亡。我认为问题出在OnTriggerEnter2d方法上。子弹穿过玩家而不杀死他们。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Bullet : MonoBehaviour
{
    float moveSpeed = 7f;
    Rigidbody2D rb;
    Player target;
    Vector2 moveDirection;

    void Start()
    {
        rb = GetComponent<Rigidbody2D>();
        target = GameObject.FindObjectOfType<Player>();
        moveDirection = (target.transform.position - transform.position).normalized * moveSpeed;
        rb.velocity = new Vector2(moveDirection.x, moveDirection.y);
        Destroy(gameObject, 3f);  
    }

    void OnTriggerEnter2D ( Collider2D col)
    {
        if(col.gameObject.name.Equals ("Player"))
        {
            Debug.Log("Hit");
            Destroy(gameObject);
        }
    }
}

标签: unity3dgame-physics

解决方案


看起来你正在摧毁子弹而不是玩家。尝试销毁属于玩家对撞机的游戏对象:

void OnTriggerEnter2D ( Collider2D col)
{
    if(col.gameObject.name.Equals ("Player"))
    {
        Debug.Log("Hit");
        Destroy(col.gameObject);
    }
}

当您说Destroy(gameObject)时,gameObject它本身是指该组件所附加到的 GameObject。和说的一样this.gameObject。由于您将组件命名为子弹,我猜这个脚本附加到一个子弹对象,因此您的播放器不会被破坏。

参见:Component.gameObject


推荐阅读