简体   繁体   中英

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. 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.

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

I don't quite understand, but if you using a rigidbody, you can try using "Quaternion.Lerp" and 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).

  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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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