首页 > 解决方案 > 在统一 3d 中旋转到原始位置

问题描述

我正在制作一个游戏,其中有一个我使用 wasd 键控制的飞机,它可以旋转和平移。到目前为止,它很好,但我希望当我举起钥匙时飞机能重新调整到原来的旋转方向。我编写的代码是这样的,但它不起作用。飞机仅重新对齐一帧,然后再次“未对齐”。这是代码-**

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

public class planemovement : MonoBehaviour
{
    public int fspeed = 10;
    float horizontal; float zrot;
    float vertical; float yrot;
    public float sense; public int lim = 0; 
    void Start()
    {


    }

    // Update is called once per frame
    void Update()
    {
        float rotz = Input.GetAxis("Vertical"); float roty = Input.GetAxis("Horizontal");
        horizontal = Input.GetAxis("Horizontal");
        vertical = Input.GetAxis("Vertical");
        transform.Translate(Vector3.forward * fspeed * Time.deltaTime);
        transform.Translate(Vector3.right * sense * Time.deltaTime * horizontal*20f);
        transform.Translate(Vector3.up * sense * Time.deltaTime * vertical);
        zrot -= rotz;
        yrot -= roty;
        zrot = Mathf.Clamp(zrot, -lim, lim);
        yrot = Mathf.Clamp(yrot, -lim, lim);
        transform.localRotation = Quaternion.Euler(zrot, 0f, yrot);


    }

}

标签: c#unity3dgame-development

解决方案


Unity C# 中的旋转通常非常不稳定,唯一准确的时间是正确使用四元数时。

public Quaternion startQuaternion;

void Start() {
    startQuaternion = transform.rotation;
}

//when you want to reset to original
transform.rotation = startQuaternion;

https://docs.unity3d.com/ScriptReference/Quaternion.html


推荐阅读