繁体   English   中英

如何在Unity3D中平滑基于加速度计的角色移动?

[英]How to smooth my accelerometer-based character movement in Unity3D?

我正在为移动平台构建一个无限的垂直平台游戏,并且正在使用加速度计左右移动播放器。 设备倾斜得越远,玩家在屏幕上移动的速度就越快。 目前,我的播放器有点太摇晃,我想在屏幕上进行更流畅的移动。 这是我移动角色的代码:

  /********************************* Variables  **************************************/

        // Variables
        float jumpForce = 700f;
        float maxSpeed;
        float acceleration;

  /********************************* Start Method ************************************/

        void Start ()
            {
            acceleration = Mathf.Abs (Input.acceleration.y);
            }

  /************************************ Fixed Update  *************************************/

        void FixedUpdate () {

                if (acceleration < 0.2f) {
                    maxSpeed = 17;
                } else if (acceleration < 0.9f) {
                    maxSpeed = 25;
                } else {
                    maxSpeed = 40;
                }

            float move = Input.acceleration.x;
                rigidbody2D.velocity = new Vector2 (move * maxSpeed, rigidbody2D.velocity.y);

    /******************************* Collision Function ******************************/

        void OnCollisionEnter2D(Collision2D coll)
            {
                foreach(ContactPoint2D contact in coll.contacts)
                {   
                     rigidbody2D.AddForce (new Vector2(0, jumpForce));
                }
            }

您不能仅使用Input.acceleration.y作为速度吗? 这样,您将不需要if条件。 如果那还不够,请乘以一个乘数。

void Update () {
    maxSpeed = Mathf.Abs(Input.acceleration.y);
    speedMultiplier = 30;

    float move = Input.acceleration.x;
    rigidbody2D.velocity = new Vector2 (move * maxSpeed * speedMultiplier, rigidbody2D.velocity.y);

之后,您只需调整speedMultiplier即可满足您的需求。
此外,如果你有一些物理工程(在这种情况下rigidbody2D.velocity ),你应该使用Update() ,而不是FixedUpdate()

您可以使用Mathf.Lerp方法来平滑速度值。

尝试使用

maxSpeed = Mathf.Lerp(maxSpeed, 17, Time.deltaTime);

代替

maxSpeed = 17;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM