c# - OnTriggerEnter2D() 似乎无法统一
问题描述
我正在开发一个平台游戏,其中一个球应该能够左右移动和跳跃。我可以使角色成功跳跃或移动,但是当我尝试检查它是否在地面上时,通过创建一个元素作为角色的子元素,使用 2D 触发器对撞机,并使用应该的变量编写代码玩家接触地面时为真,不接触地面时为假,只是没有激活。
这是主要移动脚本的代码:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Grounded : MonoBehaviour
{
GameObject Player;
// Start is called before the first frame update
void Start()
{
Player = gameObject.transform.parent.gameObject;
}
// Update is called once per frame
void Update()
{
}
private void OnTriggerEnter2D(Collider2D collision)
{
if (GetComponent<Collider2D>().tag == "Ground")
{
Player.GetComponent<Move2D>().isGrounded = true;
}
}
private void OnTriggerExit2D(Collider2D collision)
{
if (GetComponent<Collider2D>().tag == "Ground")
{
Player.GetComponent<Move2D>().isGrounded = true;
}
}
}
这是接地脚本:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Move2D : MonoBehaviour
{
public float moveSpeed = 5f;
public bool isGrounded = false;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
Jump();
Vector3 movement = new Vector3(Input.GetAxis("Horizontal"), 0f, 0f);
transform.position += movement * Time.deltaTime * moveSpeed;
}
void Jump()
{
if (Input.GetButtonDown("Jump") && isGrounded)
{
gameObject.GetComponent<Rigidbody2D>().AddForce(new Vector3(0f, 5f), ForceMode2D.Impulse);
}
}
}
非常感谢任何帮助或信息。
解决方案
你能检查一下球和地面都有刚体吗?这是触发触发器所必需的。
*注意:仅当其中一个碰撞器还附加了刚体时才会发送触发事件。*
你也可以改变你的代码
private void OnTriggerEnter2D(Collider2D collision)
{
if (GetComponent<Collider2D>().tag == "Ground")
{
Player.GetComponent<Move2D>().isGrounded = true;
}
}
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.tag == "Ground")
{
Player.GetComponent<Move2D>().isGrounded = true;
}
}
另外我还建议使用“层”而不是使用标签
推荐阅读
- php - 带有附加字符串的 Woocommerce URL
- django - 使用 ModelForms 保存 ManyToManyFields
- amazon-web-services - 亚马逊弹性搜索中的索引元数据是否适用于加密内容?
- datatables - Datatables excel pdf按钮不显示 - jquery datatable
- django - 如何通过请求从 django 模板发送数据以查看功能?
- python - 在 sql 查询中绑定列表很大的列表
- asp.net-mvc - MVC 项目中没有 sln 文件。有什么办法生成吗?
- ruby - 如何使用我的代码中使用的拆分方法生成预期的输出?
- c# - 通过整个调用堆栈轻松在异步和同步之间切换(用于调试)
- c# - 向文本文件中的现有文本添加空格和字符