首页 > 解决方案 > 如何编写代码来扣除一个生命值?

问题描述

在一个单位上研究篮球射手。我正在做负责减去生命细胞的部分。当你触摸“Bonus”组件并添加积分时,会触发负责加分的部分代码,但下一部分负责减少健康的代码不起作用。按照设计,这应该发生在球没有击中“Bonus”对象并与“Terraine”对象接触之后。如何编写代码,以便如果没有与“Bonus”对象接触,然后与“Terraine”对象发生接触,则减去一个生命值?

public GameObject hp3;
public GameObject hp2;
public GameObject hp1;

int score = 0;
int best = 0;

void Awake()
{
    rb = GetComponent<Rigidbody>();
    col = GetComponent<Collider>();

    //instance = this;
}

private void Start()
{
    best = PlayerPrefs.GetInt("best", 0);

    scoreText.text = "Score: " + score.ToString();
    bestScoreText.text = "Best: " + best.ToString();
}

public void Push(Vector2 force)
{
    rb.AddForce(force, ForceMode.Impulse);
}

public void ActivateRb()
{
    rb.isKinematic = false;
}

public void DesactivateRb()
{
    rb.velocity = Vector3.zero;
    //rb.angularVelocity = 0f;
    rb.isKinematic = true;
}

private void OnCollisionEnter(Collision collision)
{
    if (collision.gameObject.name == "Terraine")
    {
        transform.position = new Vector3(Random.Range(-4f, 8f), Random.Range(2f, 7f), -0.2f);
        DesactivateRb();
    }
}

public void OnTriggerExit(Collider other)
{
    if (other.gameObject.name == "Bonus")
    {
        score += 2;
        scoreText.text = "Score: " + score.ToString();
        if (best < score)
            PlayerPrefs.SetInt("best", score);
    }

    if (other.gameObject.name != "Bonus")
    {
        health = health - 1;
    }
}

void Update()
{
    if (health == 3)
    {
        hp3.SetActive(true);
        hp2.SetActive(false);
        hp1.SetActive(false);
    }
    if (health == 2)
    {
        hp3.SetActive(false);
        hp2.SetActive(true);
        hp1.SetActive(false);
    }
    if (health == 1)
    {
        hp3.SetActive(false);
        hp2.SetActive(false);
        hp1.SetActive(true);
    }
}

标签: c#unity3d

解决方案


不知道c#,但是像这样简单的东西会起作用吗?没有逻辑很难知道。

private void OnCollisionEnter(Collision collision)
{
    if (collision.gameObject.name == "Terraine")
    {
        transform.position = new Vector3(Random.Range(-4f, 8f), Random.Range(2f, 7f), -0.2f);
        DesactivateRb();
        if (flag != 1)
        {
        health = health - 1;
        }
        else
        {
        flag = 0;    //reset flag if 1
        }
    }
}

public void OnTriggerExit(Collider other)
{
    if (other.gameObject.name == "Bonus")
    {
        score += 2;
        flag = 1;
        scoreText.text = "Score: " + score.ToString();
        if (best < score)
            PlayerPrefs.SetInt("best", score);
    }

}

推荐阅读