【发布时间】:2019-08-01 18:18:05
【问题描述】:
我制作了一个生命值为 10 的玩家。每次被击中,他都会失去 1 点生命值。可以在健康栏中看到差异。为了让玩家有机会抵御一波又一波的敌人,我尝试重新创建生命值拾取。
我编写代码是为了让玩家得到治疗,到目前为止它会在玩家走过图标时触发,但由于某种原因,玩家没有得到治疗?
为了利用这一切,我有 2 个代码文档。
下面的第一个是健康拾取器上添加的代码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class HealthPickup : MonoBehaviour
{
Health health;
public float healthBonus;
void Awake()
{
health = FindObjectOfType<Health>();
}
void OnTriggerEnter2D(Collider2D other)
{
if(other.GetComponent<Player>() == null)
return;
if(health.health < health.maxHealth)
health.health = health.health + (int)healthBonus;
{
Destroy(gameObject);
}
}
}
以下代码是玩家健康的代码。
[Header ("Max/Starting Health")]
public int maxHealth;
[Header ("Current Health")]
public int health;
void Start () {
health = maxHealth;
}
public bool TakeHeal (int amount) {
if (dead || health == maxHealth)
return false;
health = Mathf.Min (maxHealth, health + amount);
if (OnTakeHealEvent != null)
OnTakeHealEvent.Invoke();
return true;
}
正如你在下面看到的,我将额外生命值设置为 3。当玩家与物体发生碰撞时,他会增加 3 点生命值。
如您所见,玩家总共有 10 点生命值。我试图减少游戏中的生命值并与物体发生碰撞。然而,没有向用户添加健康。
如您所见,玩家现在有 7 点生命值(3.5 格)
当我走过血条时,玩家的血量 (7) 仍然保持不变。即使对撞机和物体的破坏也能完全发挥作用。
伤害播放器功能
protected virtual void Awake () {
if (Owner == null) {
Owner = gameObject;
}
}
public virtual void OnTriggerEnter2D(Collider2D collider)
{
Colliding (collider);
}
public virtual void OnTriggerStay2D(Collider2D collider)
{
Colliding (collider);
}
protected virtual void Colliding(Collider2D collider)
{
if (!isActiveAndEnabled) {
return;
}
// if what we're colliding with isn't the target tag, we do nothing and exit
if (!collider.gameObject.CompareTag(TargetTag)) {
return;
}
var health = collider.gameObject.GetComponent<Health>();
// If what we're colliding with is damageable / Has health component
if (health != null)
{
if(health.health > 0 && !health.invincible)
{
// Apply the Damage
health.TakeDamage(DamageToCause);
}
【问题讨论】:
-
你试过调试这个吗?您的代码存在于您的问题中的方式,我看不出它不起作用的原因。请向我们提供更多信息以帮助您。
-
我会提供更多的截图让大家更清楚,给我一点时间来做
-
你在哪里打电话给
TakeHeal? -
嗨@MikeH 在这种情况下我根本没有打电话给TakeHeal,而是专注于使用基本的健康功能。我认为这足以看看它是否会增加任何 HP。
-
可能是因为您在调用 Take Heal 时调用了一个动作,并且在您的触发器中您只是添加了健康状况而不是调用您的 TakeHeal 函数>