为什么我的播放器卡在墙上 Unity 2D

Why is my player getting stuck in walls Unity 2D

我正在用 unity 2d 制作游戏,当我的玩家撞到墙上时,他被卡住了,根本无法移动。这是一个视频:

VIDEO

我试过使用复合对撞机,物理学 material,摩擦力为 0。

这是我的动作脚本:

public class PlayerMovement : MonoBehaviour
{
    Vector3 pos;
    float speed = 2.0f;
    private Animator animator;
    void Start()
    {
        pos = transform.position;
        animator = gameObject.GetComponent<Animator>();
    }

    void FixedUpdate()
    {
        if (Input.GetKey(KeyCode.W) && transform.position == pos)
        {        // Up
            animator.SetInteger("isWalking", 1);
            pos += Vector3.up;
        }
        if (Input.GetKey(KeyCode.S) && transform.position == pos)
        {        // Down
            animator.SetInteger("isWalking", 2);
            pos += Vector3.down;
        }
        if (Input.GetKey(KeyCode.D) && transform.position == pos)
        {        // Right
            animator.SetInteger("isWalking", 3);
            pos += Vector3.right;
        }
        if (Input.GetKey(KeyCode.A) && transform.position == pos)
        {        // Left
            animator.SetInteger("isWalking", 4);
            pos += Vector3.left;
        }
        if (Input.anyKey == false)
            animator.SetInteger("isWalking", 0);
        transform.position = Vector3.MoveTowards(transform.position, pos, Time.deltaTime * speed);
    }
}

您案例中的 Player 对象包含一个 Rigidbody 组件。因此,最好使用一些 Rigidbody 的移动方法,如 MovePosition() 而不是直接通过 transform.position

改变 GameObject 的位置

感谢@Nitro557,我有了一个新想法,而不是简单地传送玩家,我使用了一种完全不同的移动玩家的方法,这里是脚本:


    public float runSpeed = 2.0f;
    private Rigidbody2D body;
    private Animator animator;
    private float horizontal;
    private float vertical;
    private float moveLimiter = 0.7f;
    void Start()
    {
        body = GetComponent<Rigidbody2D>();
        animator = GetComponent<Animator>();
    }
    void Update()
    {
        horizontal = Input.GetAxisRaw("Horizontal");
        vertical = Input.GetAxisRaw("Vertical");
        if(Input.GetKeyDown(KeyCode.LeftShift))
        {
            runSpeed += 0.5f;
        }
    }
    private void FixedUpdate()
    {
        if (horizontal != 0 && vertical != 0)
        {
            horizontal *= moveLimiter;
            vertical *= moveLimiter;
        }
        body.velocity = new Vector2(horizontal * runSpeed, vertical * runSpeed);
        // Up
        if (Input.GetKey(KeyCode.W))
            animator.SetInteger("isWalking", 1);
        // Down
        if (Input.GetKey(KeyCode.S))
            animator.SetInteger("isWalking", 2);
        // Right
        if (Input.GetKey(KeyCode.D))
            animator.SetInteger("isWalking", 3);
        // Left
        if (Input.GetKey(KeyCode.A))
            animator.SetInteger("isWalking", 4);
        if (Input.anyKeyDown == false)
            animator.SetInteger("isWalking", 0);
        body.velocity = new Vector2(horizontal * runSpeed, vertical * runSpeed);
    }