记录个人学习unity中遇到的坑(一)——2D角色撞墙左右抽搐问题

出现该问题的代码如下:

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayController : MonoBehaviour
{
    
    
    [Header("移动参数")]
    public Vector2 currentVelocity;
    public float xInput;
    public float LRMoveForce;
   private void Start()
    {
    
    
        pos = GetComponent<Transform>();
        rb = GetComponent<Rigidbody2D>();
    }
    private void Update()
    {
    
    
        LRMovement();
    }

  private void LRMovement()
    {
    
    
        if (rb.velocity.x < 0)
        {
    
    
            faceDir = -1;
            pos.rotation = Quaternion.Euler(0, 180, 0);
            //transform.localScale = new Vector3(-1, 1, 1);

        }
        if (rb.velocity.x > 0)
        {
    
    
            faceDir = 1;
            pos.rotation = Quaternion.Euler(0, 0, 0);
            //transform.localScale = new Vector3(1, 1, 1);
        }

        xInput = Input.GetAxisRaw("Horizontal");      
        rb.velocity = new Vector2(xInput * LRMoveForce, rb.velocity.y);
        currentVelocity = rb.velocity;
    }
}

该脚本挂载在player上,当player在水平方向上遇到static刚体的collider时持续按下移动键可能会发生角色左右抽搐的情况。同时观察到position.x会在极小范围内抖动,potion.y会以极小的速率递减。

无论是将物体左右翻转的方式改为修改loaclscale,还是将物体移动的方式由修改velocity改为addforce均无法解决问题。

可行的解决方案:判断物体朝向的代码不放在rb.velocity.x的判断下,修改后的代码如下

   private void LRMovement()
    {
    
    
        if (rb.velocity.x < 0)
        {
    
    
            faceDir = -1;
            //pos.rotation = Quaternion.Euler(0, 180, 0);
            //transform.localScale = new Vector3(-1, 1, 1);

        }
        if (rb.velocity.x > 0)
        {
    
    
            faceDir = 1;
            //pos.rotation = Quaternion.Euler(0, 0, 0);
            //transform.localScale = new Vector3(1, 1, 1);
        }

        xInput = Input.GetAxisRaw("Horizontal");
        if (xInput < 0)
        {
    
    
            pos.rotation = Quaternion.Euler(0, 180, 0);
        }
        if (xInput > 0)
        {
    
    
            pos.rotation = Quaternion.Euler(0, 0, 0);
        }
        rb.velocity = new Vector2(xInput * LRMoveForce, rb.velocity.y);
        currentVelocity = rb.velocity;
    }

(第一次尝试制作游戏,不是很有经验,如果有更好的方法或者知道原因的也希望各位能在评论区指出。)

猜你喜欢

转载自blog.csdn.net/wsWind/article/details/108966363