简体   繁体   中英

How to check for collision in if-statement

I have method to buy a tile and i need to check if it collides with another tile owned by player.

I know about func OnCollisionEnter and etc but i think i need other way and check it in if-statement.

void BuyTile()
{
    if (_selected.tag == "Free") // if no owners
    {
        _selected.GetComponent<Renderer>().material.color = Color.green;
        _selected.tag = "Player1";
        pc.CountTiles();
    }
    _selected = null;
}

i need smth like that if (_selected.tag == "Free" && _selected.CollideWithGO.tag == "Player1") but idk how to do that using no func

Keep track of the collision:

public class CollisionTracker : MonoBehaviour
{
    Collision collision;

    void Update()
    {
        if (collision != null && collision.gameObject.tag == "Player")
        {
            Debug.Log("Colliding with Player!");
        }
    }

    void OnCollisionEnter(Collision collision)
    {
        this.collision = collision;
    }

    void OnCollisionExit(Collision collision)
    {
        this.collision = null;
    }
}

ps: solve it

bool Neighboor(GameObject centerTarget)
{
    bool GotTrue = false;
    Collider[] hitColliders = Physics.OverlapSphere(centerTarget.transform.position, 1f);
    for (int i = 0; i<hitColliders.Length; i++)
    {
        if(hitColliders[i].tag == "Player1")
        {
            GotTrue = true;
            break;
        }
    }
    if (GotTrue)
        return true;
    else return false;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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