Search code examples
c#unity-game-enginerotationlogicquaternions

C# programming logic (Unity3d script)


I have a script for player to open and close the door but when I press the button to close the door, it goes closes and then goes open again. I suspect it is because the lerp doesn't stop or something. How can I fix this? What's wrong? Thanks!

Door Script:

using UnityEngine;
using System.Collections;

public class DoorHandler : MonoBehaviour {
public bool isOpen = false;
public float maxOpenDistance = 10f, doorCloseTime = 3f;

void Update () {
    if (Input.GetKeyDown (KeyCode.F)) {
        if (Vector3.Distance (GameObject.FindGameObjectWithTag ("Player").transform.position, this.gameObject.transform.position) <= maxOpenDistance) {
            isOpen = !isOpen;
        }

    if (isOpen) 
        gameObject.transform.rotation = Quaternion.Lerp (Quaternion.Euler (transform.rotation.x, 0, transform.rotation.z),
                                                                 Quaternion.Euler (transform.rotation.x, 90, transform.rotation.z), doorCloseTime);
        } else {
        gameObject.transform.rotation = Quaternion.Lerp (Quaternion.Euler (transform.rotation.x, 90, transform.rotation.z),
                                                               Quaternion.Euler (transform.rotation.x, 0, transform.rotation.z), doorCloseTime);
    } 
}
}

Solution

  • You have set your curly brackets wrong. You should check if your IDE has an autoformatting function, so you can easily find those errors.

    void Update () {
        if (Input.GetKeyDown (KeyCode.F)) {
            if (Vector3.Distance (GameObject.FindGameObjectWithTag ("Player").transform.position, this.gameObject.transform.position) <= maxOpenDistance) {
                isOpen = !isOpen;
            }
        }
    
        if (isOpen) 
            gameObject.transform.rotation = Quaternion.Lerp (Quaternion.Euler (transform.rotation.x, 0, transform.rotation.z),
                                                             Quaternion.Euler (transform.rotation.x, 90, transform.rotation.z), doorCloseTime);
        else {
            gameObject.transform.rotation = Quaternion.Lerp (Quaternion.Euler (transform.rotation.x, 90, transform.rotation.z),
                                                             Quaternion.Euler (transform.rotation.x, 0, transform.rotation.z), doorCloseTime);
        } 
    }
    

    Also I don't know if you set another value for doorCloseTime in the inspector, but 3 doesn't make any sense. Lerp does a linear interpolation between two values. The reference value (t), that you specify in the Lerp method should ideally be a value between 0 and 1. And last, you should also set an appropriate from value in the Lerp method. Assuming you want to have a smooth transition, you may want to use the current rotation instead of a hard coded Quaternion.