简体   繁体   English

尝试编写一个 2D Unity 代码,以显示我的角色是否已接地且无法正常工作

[英]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.我正在尝试进行 2D 跳跃运动。 It's either the Collisions2D couldn't find GetComponent or the game works but the character doesn't jump at all.要么是Collisions2D找不到GetComponent要么是游戏运行正常,但角色根本没有跳跃。

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.tag == "Ground"代替。

col.collider refers to the incomming collider, in your case ground. col.collider指的是col.collider的对撞机,在您的情况下为地面。 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. col.otherCollider可用于调用其他碰撞器,在您的情况下是播放器本身。 This can be useful when have a lot of collisions.这在有很多碰撞时很有用。

Feel free to ask for more help is this wasn't enough.如果这还不够,请随时寻求更多帮助。

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

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