简体   繁体   English

如何在 Unity 2D 中的 if 语句中检查碰撞

[英]How to check for collision in an if statement in Unity 2D

I have a script that counts down from 20 to 0, then when it reaches 0 a boolean is set to true.我有一个从 20 倒计时到 0 的脚本,然后当它达到 0 时,boolean 设置为 true。 What I want that boolean to do is write something on the console when the player is collided with the sprite the script is on, but I only want this to happen if it's true.我希望 boolean 做的是当玩家与脚本所在的精灵发生碰撞时在控制台上写一些东西,但我只希望这发生在它是真的。 Here's the code:这是代码:

public float timeLeft = 10f;
public bool canHarvest;

public void Start()
{
    canHarvest = false;
}


public void Update()
{
    timeLeft -= Time.deltaTime;



    if (timeLeft < 0)
    {
        Debug.Log("IM READY TO HARVEST");
        canHarvest = true;

    }

    if (canHarvest = true)
    {
        public void OnTriggerEnter2D(Collider2D col)
        {
            if (col.gameObject.tag == "Player")
            {
                Debug.Log("true");
            }
        }
    }



}

} }

What I want this code to do is set canHarvest to false at the start (meaning that if the player collides with the object the script is on nothing will happen), and once timeLeft reaches 0 it should set canHarvest to true, meaning that if the player collides with the object the script is on, the object the script is on will disappear.我希望这段代码在开始时将 canHarvest 设置为 false(这意味着如果玩家与 object 发生碰撞,则脚本不会发生任何事情),一旦 timeLeft 达到 0,它应该将 canHarvest 设置为 true,这意味着如果播放器与脚本打开的 object 发生碰撞,脚本打开的 object 将消失。 This is not working as I can't have the if statement checking if the player collides inside the if statement checking if canHarvest is true.这不起作用,因为我不能让 if 语句检查玩家是否在 if 语句中发生碰撞,检查 canHarvest 是否为真。 Please help!请帮忙!

You should move the OnTriggerEnter2D definition outside the Update() method and conditional check should be inside the function:您应该将 OnTriggerEnter2D 定义移到 Update() 方法之外,条件检查应该在 function 内:

public float timeLeft = 10f;
public bool canHarvest;

public void Start()
{
    canHarvest = false;
}

public void Update()
{
    timeLeft -= Time.deltaTime;

    if (timeLeft < 0)
    {
        Debug.Log("IM READY TO HARVEST");
        canHarvest = true;    
    }      
}

public void OnTriggerEnter2D(Collider2D col)
{
     if (canHarvest && col.gameObject.tag == "Player")
     {
         Debug.Log("true");
     }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM