unity3d - 当子弹碰到他时玩家不会死
问题描述
我的玩家在被我坦克的子弹击中时不会死亡。我认为问题出在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);
}
}
}
解决方案
看起来你正在摧毁子弹而不是玩家。尝试销毁属于玩家对撞机的游戏对象:
void OnTriggerEnter2D ( Collider2D col)
{
if(col.gameObject.name.Equals ("Player"))
{
Debug.Log("Hit");
Destroy(col.gameObject);
}
}
当您说Destroy(gameObject)
时,gameObject
它本身是指该组件所附加到的 GameObject。和说的一样this.gameObject
。由于您将组件命名为子弹,我猜这个脚本附加到一个子弹对象,因此您的播放器不会被破坏。
推荐阅读
- r - 使用 st_distance 计算到特定点的最近距离
- python - 使用python从模块调用主文件中的内部函数
- python - 如何比较两个数据框并使用新值进行更新
- flutter - ExpansionTile 溢出
- ffmpeg - ffmpeg - 在组合多个图像和音轨时对输入图像应用填充
- oracle-apex - 如何在 Oracle Apex 交互式报表的行中添加更新按钮?
- java - 将 UTC 日期转换为给定时区时的值错误
- c# - ASP.net Core - JsonProperty NullValueHandling.Ignore 不适用于可空类型
- java - Java Applet 有危险吗?
- python - 按顺序绘制带有 y 轴的图形