如何正确轮换和优化

how to rotate and optimize properly

我是编程新手,我正在开发这款游戏 我需要帮助,我正在使用 unity。

我试图让 obj 稍微向左或向右旋转,但如果我同时开始按下按钮,则旋转不匹配。同时这段代码似乎效率不高,我该如何解决?

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

public class Character2DController : MonoBehaviour
{

    public float MovementSpeed = 1;



    private Rigidbody2D _rigidbody;


    // Start is called before the first frame update
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {
        var movement = Input.GetAxis("Horizontal");
        transform.position += new Vector3(movement, 0, 0) * Time.deltaTime * MovementSpeed;
        if (Input.GetKeyDown("a"))
        {
            RotateLeft();
        }
        else if (Input.GetKeyDown("d"))
        {
            RotateRight();
        }
        else if (Input.GetKeyUp("a"))
        {
            ResetRotateLeft();
        }
        else if (Input.GetKeyUp("d"))
        {
            ResetRotateLeft();
        }




        void RotateLeft()
        {
            transform.eulerAngles = new Vector3(0, 0, 10);
        }

        void ResetRotateLeft()
        {
            transform.eulerAngles = new Vector3(0, 0, 0);
        }





        void RotateRight()
        {
            transform.eulerAngles = new Vector3(0, 0, -10);
        }


    }

}

这应该对您有帮助:

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

public class Character2DController : MonoBehaviour
{

    public float MovementSpeed = 1;
    public float RotationSpeed = 10;
    private Rigidbody2D _rigidbody = null;
    private float angle = 10;
    private float currentAngle = 0;

    private void Update()
    {
        float movement = Input.GetAxis("Horizontal");
        float targetAngle = 0;
        if(movement > 0)
        {
            targetAngle = -angle;
        }
        else if (movement < 0)
        {
            targetAngle = angle;
        }
        transform.position += new Vector3(movement, 0, 0) * Time.deltaTime * MovementSpeed;
        currentAngle = Mathf.Lerp(currentAngle, targetAngle, RotationSpeed * Time.deltaTime);
        transform.eulerAngles = new Vector3(0, 0, currentAngle);
    }
}