我在我的Unity游戏引擎中穿过地面。有人知道我为什么穿过地面吗?我正在遵循教程:https://www.youtube.com/watch?v=LEUhxe9vUOM&list=PLrnPJCHvNZuCVTz6lvhR81nnaf1a-b67U&index=6&ab_channel=CodinginFlow。
下面是我的PlayerMovement代码(我将其命名为PlayerMovementProject4.cs
):
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovementProject4 : MonoBehaviour
{
private Rigidbody2D rb; //Will store appropriate Rigidbody2D from PlayerMovement
private Animator anim;
[SerializeField] private LayerMask jumpableGround;
private float dirX = 0f;
private SpriteRenderer sr;
private BoxCollider2D coll;
[SerializeField] private float moveSpeed = 7f;
[SerializeField] private float jumpForce = 14f;
private enum MovementState { idle, running, jumping, falling}
// Start is called before the first frame update
private void Start()
{
rb = GetComponent<Rigidbody2D>();
coll = GetComponent<BoxCollider2D>();
sr = GetComponent<SpriteRenderer>();
anim = GetComponent<Animator>();
}
// Update is called once per frame
private void Update()
{
dirX = Input.GetAxis("Horizontal"); //Might be appropriate to change to GetAxisRaw
rb.velocity = new Vector2(dirX * 7f, rb.velocity.y);
if (Input.GetButtonDown("Jump") && IsGrounded())
{
rb.velocity = new Vector2(rb.velocity.x, jumpForce);
}
UpdateAnimationUpdate();
}
private void UpdateAnimationUpdate() //Will be used to handle Animations
{
MovementState myMovementState;
if (dirX > 0f)
{
myMovementState = MovementState.running;
sr.flipX = false;
}
else if (dirX < 0f)
{
myMovementState = MovementState.running;
sr.flipX = true;
}
else //Exactly 0
{
myMovementState = MovementState.idle;
}
if (rb.velocity.y > 0.1f)
{
myMovementState = MovementState.jumping;
}
else if (rb.velocity.y < -0.1f)
{
myMovementState = MovementState.falling;
}
anim.SetInteger("state", (int)(myMovementState));
}
private void UpdateAnimationUpdate(float ff) //Might need to use this
{
dirX = ff;
UpdateAnimationUpdate(); //DO NOT REPEAT CODE (DRY)
}
private bool IsGrounded()
{
return Physics2D.BoxCast(coll.bounds.center, coll.bounds.size, 0f, Vector2.down, .1f, jumpableGround);
}
}
另外,这里是我得到的错误的屏幕截图:
如果有人能帮助我,我将不胜感激。
谢谢你!
1条答案
按热度按时间cunj1qz11#
我建议在项目设置〉物理2D中检查碰撞矩阵,以及游戏对象的层。
如果不是碰撞矩阵,也可以检查你的游戏对象上的碰撞器组件。为了让一个对象在2D游戏中不穿过另一个对象,两个对象上都应该有任何类型的Collider2d,并且应该取消选中isTrigger。
另外,当得到NullReferenceException时,这意味着脚本无法找到它需要继续的引用内容,你应该检查是否所有内容都正确地添加到正确的游戏对象或正确地创建,我不确定你是否知道你发布的日志不是来自你的脚本,请先确定它来自哪里,看看缺少了什么。