简体   繁体   English

如何通过在 Unity3d 中按下按钮来获得平滑的相机旋转

[英]How to get a Smooth Camera Rotation via button press in Unity3d

I'm relatively new to Unity so my experience in writing code is limited.我对 Unity 比较陌生,所以我在编写代码方面的经验有限。

I made a camera script that upon button press, rotates the camera on the y-axis, relative to the world space.我制作了一个相机脚本,当按下按钮时,相对于世界空间在 y 轴上旋转相机。 It works, but its instantaneous.它有效,但它是瞬间的。 Without affecting its rotation speed or the other axes, I want to show a smooth rotation to its target axis.在不影响其旋转速度或其他轴的情况下,我想显示其目标轴的平滑旋转。 Here is the code:这是代码:

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

public class CameraRotation : MonoBehaviour
{
    public float camRotationSpeed = 90f;
    float camRotation;


    private void LateUpdate()
    {
        RotateCamera();
    }

    void RotateCamera()
    {
        camRotation = Input.GetAxis("Camera Rotate") * camRotationSpeed;

        if (Input.GetButtonDown("Camera Rotate")) 
        {
            gameObject.transform.Rotate(0, camRotation, 0, Space.World);
        }
    }
}

For these kinds of tasks, I would suggest you use tweeting libraries.对于这些类型的任务,我建议您使用推文库。 These quite a few libraries on Unity Asset-Store some of them are free to use. Unity Asset-Store上有不少库,其中一些可以免费使用。 Since I only used DoTween I can only tell you about that.因为我只用过DoTween,所以我只能告诉你这个。

You can also achieve this by using CoRoutines as well.您也可以通过使用 CoRoutine 来实现这一点。 But they tend to be memory intensive sometimes.但有时它们往往是内存密集型的。

Solution:解决方案:

float camRotationDuration = 0.5f; //This value is in seconds
bool isCameraRotating = false;
void RotateCamera()
{
    camRotation = Input.GetAxis("Camera Rotate") * camRotationSpeed;

    if (Input.GetButtonDown("Camera Rotate")) 
    {
        if (!isCameraRotating)
        {
            transform.DORotate(new Vector3(0, camRotation , 0), camRotationDuration);
            isCameraRotating = true;
            Invoke("SetCameraRotateToFalse", camRotationDuration);
        }
    }
}

private void SetCameraRotateToFalse()
{
    isCameraRotating = false;
}

Please take a look at the DoTween documentation that I've added to the bottom of the answer in case you want to use this.如果您想使用它,请查看我添加到答案底部的 DoTween 文档。

Reference:参考:
DoTween Documentation DoTween 文档

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

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