【问题标题】:rotation to original position in unity 3d在统一 3d 中旋转到原始位置
【发布时间】:2020-05-23 17:04:46
【问题描述】:

我正在制作一个游戏,其中有一个我使用 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# unity3d game-development


    【解决方案1】:

    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

    【讨论】:

      【解决方案2】:

      我不太明白,但是如果您使用刚体,您可以尝试使用“Quaternion.Lerp”和 MoveRotation。 Quaternion.Lerp 具有三个参数,并创建从 A 点到 B 点的旋转,速度为 ugual 到 T(T 从 0 到 1)。

        var currentRot = transform.rotation
      var desired Rot = rotation on which the plane must be aligned
      Quaternion RotPlane = Quaternion.Lerp (currentRot, desiredRot, 0.5)
      MoveRotation(RotPlane)
      

      您可以使用 if (Input.GetKeyUp) 并将脚本放在其下方,因此每次您释放按钮时,飞机都会返回所需的旋转。

      【讨论】:

        猜你喜欢
        • 2011-12-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-07-14
        • 2019-07-04
        • 1970-01-01
        相关资源
        最近更新 更多