Tilemap 的网格在 Unity 中停止角色

问题描述 投票:0回答:0

当角色跳跃并跑到墙上时,他会在墙前停一个或多个方格,如果他不跳,他会不停地跑。当他停止时,他的对撞机不会与 tilemap 的对撞机发生碰撞。为什么他在没有墙的时候停下来?

视频:https://youtu.be/FYNYEsMDa1Y

using UnityEngine;

public class PlayerMover : MonoBehaviour
{
[SerializeField] private float _speed;
[SerializeField] private float _narrowBoxcast;
[SerializeField] private float _jumpDistance;
[SerializeField] private float _rayRange;
[SerializeField] private LayerMask _layerTilemap;

private Rigidbody2D _rigidbody;
private BoxCollider2D _collider;
private Vector2 _velocity;
private float _direction;
private bool _isGrounded;

public Vector2 Velocity => _velocity;
public bool IsGrounded => _isGrounded;

private void Start()
{
    _collider = GetComponent<BoxCollider2D>();
    _rigidbody = GetComponent<Rigidbody2D>();
}

void Update()
{
    CheckIsGrounded();

    if (Input.GetKeyDown(KeyCode.Space) && _isGrounded)
        Jump();
}

private void FixedUpdate()
{
    Move();
}

private void Move()
{
    _direction = Input.GetAxisRaw("Horizontal");
    _velocity = new Vector2(_speed * _direction, _rigidbody.velocity.y);
    _rigidbody.velocity = _velocity;
}

private void Jump()
{
    _rigidbody.velocity = new Vector2(_rigidbody.velocity.x, _jumpDistance);
}

private void CheckIsGrounded()
{
    RaycastHit2D hit = Physics2D.BoxCast(_collider.bounds.center, _collider.bounds.size - new Vector3(_narrowBoxcast, 0f, 0f), 0f,
                                         Vector2.down, _rayRange, _layerTilemap);

    if (hit.collider != null)
        _isGrounded = true;
    else
        _isGrounded = false;
}
}
c# unity3d
© www.soinside.com 2019 - 2024. All rights reserved.