【问题标题】:Unity 2D, C# - Why my OnCollisionEnter2D doesn't collide?Unity 2D,C# - 为什么我的 OnCollisionEnter2D 不碰撞?
【发布时间】:2019-06-18 00:37:27
【问题描述】:

所以,我创建了两个脚本,一个名为“Stats.cs”的脚本注册玩家统计数据,另一个名为“PlayerHealth.cs”的脚本“使”玩家在接触时受到伤害并更新 HUD 中的 Hearts。我的问题是,每当我与一个带有“Projectile”标签的物体发生碰撞时,它根本不起作用,我的玩家根本不会受到伤害。 Stats.cs 脚本不在任何对象中,PlayerHealth.cs 在我的 Player 对象中。

Stats.cs

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

[System.Serializable]
public class Stats{

private int health;

public int maxHP = 3;

public int Health
{
    get
    {
        //Some code
        return health;
    }
    set
    {
        //Some code
        health = Mathf.Clamp(value, 0, maxHP);
    }
}
public void SetHealth()
{
    Health = maxHP;
}
}

PlayerHealth.cs

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

public class PlayerHealth : MonoBehaviour
{
Stats playerStats = new Stats();

public int curHealth;
public int numOfHearts = 3;

public Image[] hearts;
public Sprite fullHeart;
public Sprite emptyHeart;

void OnCollisionEnter2D(Collision2D other)
{
    if (other.gameObject.CompareTag("Projectile"))
    {
        Debug.Log("Hello");
        DamagePlayer(1);
        Destroy(other.gameObject);
    }
}

public void DamagePlayer(int damage)
{
    playerStats.Health -= damage;
}

// Start is called before the first frame update
void Start()
{
    playerStats.SetHealth();
    curHealth = numOfHearts;
}

// Update is called once per frame
void Update()
{

    curHealth = playerStats.Health;
    numOfHearts = playerStats.maxHP;

    if (curHealth>numOfHearts){
        curHealth = numOfHearts;
    }
    if(curHealth <= 0){

        Die();

    }

    for (int i = 0; i < hearts.Length; i++)
    {
        if(i < curHealth){
            hearts[i].sprite = fullHeart;
        } else
        {
            hearts[i].sprite = emptyHeart;
        }

        if(i < numOfHearts){
            hearts[i].enabled = true;
        } else {
            hearts[i].enabled = false;
        }

    }
}

void Die(){
    //Restart
    Application.LoadLevel(Application.loadedLevel);
}


}

curHealth 正在更新,因此它将保持为 Stats 中的实际健康状况,并将更改 HUD 中的图像。

Player身上有一个RigidBody2D,有两个collider,一个是body的box,一个是circlecollider,所以当玩家蹲下时,圆形collider失效。

Projectiles 还具有重力为 0 的 RigidBody2D(因此它不会落到半空中)和 BoxCollider2D。

【问题讨论】:

  • 从你的帖子中并不能完全清楚什么是有效的,什么是无效的。
  • 你的对撞机之一是触发器吗?如果是这样,请确保在 Project Settings>Physics>Collision matrix 中,您的图层正在碰撞,并选中“Queries Hit Trigger”。加上使用 OnTriggerEnter2D 而不是 OnCollisionEnter2D
  • 你的Debug.Log("Hello"); 有没有接到电话?

标签: c# unity3d


【解决方案1】:

我会检查并确保弹丸被标记为 Projectile 并且 BoxCollider 没有选中“Is Trigger”。

我还应该说,在 Update 中使用 for 循环进行迭代在实践性能方面非常糟糕。这种情况发生的速度与机器循环播放的速度一样快,并且每次都在这样做。我会考虑在活动中更新它。

希望这会有所帮助!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-02-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-31
    相关资源
    最近更新 更多