尝试编写一个 2D Unity 代码来显示我的角色是否接地并且它不起作用
Trying to program a 2D Unity code that shows if my character is grounded or not and it's not working
我怎样才能让角色认出它是地面?我正在尝试进行 2D 跳跃运动。可能是 Collisions2D
找不到 GetComponent
或游戏正常但角色根本不跳。
错误:
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
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;
}
}
}
请尝试使用 col.collider.tag == "Ground"
。
col.collider
指的是进入的对撞机,在你的情况下是地面。因为那是你正在与之碰撞的对撞机(当然只有当你接触地面时)。
col.otherCollider
可用于调用另一个对撞机,在您的情况下是玩家本身。这在有很多碰撞时很有用。
如果这还不够,请随时寻求更多帮助。
我怎样才能让角色认出它是地面?我正在尝试进行 2D 跳跃运动。可能是 Collisions2D
找不到 GetComponent
或游戏正常但角色根本不跳。
错误:
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
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;
}
}
}
请尝试使用 col.collider.tag == "Ground"
。
col.collider
指的是进入的对撞机,在你的情况下是地面。因为那是你正在与之碰撞的对撞机(当然只有当你接触地面时)。
col.otherCollider
可用于调用另一个对撞机,在您的情况下是玩家本身。这在有很多碰撞时很有用。
如果这还不够,请随时寻求更多帮助。