简体   繁体   English

旋转到原始 position 统一 3d

[英]rotation to original position in unity 3d

I was making a game where there is a plane which I control using the wasd keys, it rotates and translates.我正在制作一个游戏,其中有一个我使用 wasd 键控制的飞机,它可以旋转和平移。 Up-to that its fine, but I would like the plane to re-align to its original rotation when I lift the key.到目前为止,它很好,但我希望当我举起钥匙时飞机能重新调整到原来的旋转方向。 The code I made up is this but it doesn't work.我编写的代码是这样的,但它不起作用。 The plane realigns for only one frame and then "misaligned" again.平面仅重新对齐一帧,然后再次“未对齐”。 This is the code -**这是代码-**

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);


    }

}

Rotation in Unity C# is usually quite wonky, the only time it is exact is when you use Quaternions properly. 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 https://docs.unity3d.com/ScriptReference/Quaternion.html

I don't quite understand, but if you using a rigidbody, you can try using "Quaternion.Lerp" and MoveRotation.我不太明白,但如果您使用刚体,您可以尝试使用“Quaternion.Lerp”和 MoveRotation。 Quaternion.Lerp has three parameters and creates a rotation from point A to B, with a speed ugual to T (T goes from 0 to 1). 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)

You can use an if (Input.GetKeyUp) and put the script underneath it, so every time you release the buttons the plane returns to the desired rotation.您可以使用 if (Input.GetKeyUp) 并将脚本放在它下面,因此每次释放按钮时,飞机都会返回所需的旋转。

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

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