简体   繁体   中英

Trying to program a 2D Unity code that shows if my character is grounded or not and it's not working

error CS1061: 'Collision2D' does not contain a definition for 'GetComponent' and no accessible extension method 'GetComponent' accepting a first argument of type 'Collision2D' could be found

How can I make the ground so that the character recognize that it is ground? I'm trying to do a 2D jump movement. It's either the Collisions2D couldn't find GetComponent or the game works but the character doesn't jump at all.

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

public class Grounded : MonoBehaviour
{
    GameObject Player;

    void Start()
    {
        Player = GetComponentInParent<GameObject>();
    }

    void Update(){
    }

    void OnCollisionEnter2D(Collision2D col) {

        if (col.GetComponent<Collider2D>().tag == "Ground") {

            Player.GetComponent<Move2D>().isGrounded = true;

        }
    }

    void OnCollisionExit2D(Collision2D col) {

        if (col.GetComponent<Collider2D>().tag == "Ground") {

            Player.GetComponent<Move2D>().isGrounded = false;

        }
    }
}

Try using col.collider.tag == "Ground" instead.

col.collider refers to the incomming collider, in your case ground. Because that's the collider that you're colliding with (only when you touch the ground of course).

col.otherCollider can be used to call the other collider, in your case the player itself. This can be useful when have a lot of collisions.

Feel free to ask for more help is this wasn't enough.

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