簡體   English   中英

Unity 2D,C#-為什么我的OnCollisionEnter2D不碰撞?

[英]Unity 2D, C# - Why my OnCollisionEnter2D doesn't collide?

因此,我創建了兩個腳本,一個名為“ 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中的實際Health,並會更改HUD中的圖像。

玩家在他的兩個對撞機上都具有RigidBody2D,一個是用於身體的盒子,另一個是圓形對撞機,因此當玩家蹲下時,圓形對撞機將禁用。

投射物還具有重力為0的RigidBody2D(這樣它就不會掉到空中)和BoxCollider2D。

我將檢查並確保將彈丸標記為“彈丸”,並且BoxCollider沒有選中“觸發”。

我也應該說,在Update中用for循環進行迭代是非常糟糕的做法。 實際上,這發生在機器可以循環的速度上,並且每次都在這樣做。 我會考慮在事件中進行更新。

希望這可以幫助!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM