Search Unity

Resolved Smooth door opening with Quaternion.Slerp issue

Discussion in 'Scripting' started by OverBoosted, Jan 25, 2024.

  1. OverBoosted

    OverBoosted

    Joined:
    Sep 10, 2021
    Posts:
    6
    Hello! I'm currently trying to make my doors open smoothly in unity by using Quaternion.Slerp, only issue is that I can't seem to get the rotation speed correct. No matter what value I use for rotation speed(float t) it immediately does the full rotation.

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class DoorLogic : MonoBehaviour
    6. {
    7.     public Transform character;
    8.     public Transform doorHandle;
    9.     public Transform pivotPoint;
    10.  
    11.     public float turnSpeed = 0.01f;
    12.  
    13.     public Quaternion currentRot;
    14.     public Quaternion targetRot;
    15.  
    16.     void Update()
    17.     {
    18.         if(character.GetComponent<DoorOpenNClose>()._selection == doorHandle && Input.GetMouseButtonDown(0))
    19.         {
    20.             pivotPoint.rotation = Quaternion.Slerp(currentRot, targetRot, turnSpeed);
    21.         }
    22.  
    23.     }
    24. }
    25.  
     
  2. orionsyndrome

    orionsyndrome

    Joined:
    May 4, 2014
    Posts:
    3,096
    Quaternion.Slerp does not work like RotateTowards, there is no speed

    All interpolating functions (such as lerp or slerp) do their thing between minimum and maximum and you're expected to supply a value in the interval 0..1 (so called interpolant) where 0 results in minimum and 1 in maximum.

    I can only advise you to read the documentation and find some videos online. There are tens of thousands of topics regarding this, doesn't make much sense to waste everyone's time.

    Btw Quaternion.Slerp specifically clamps this interpolant, so if you're consistently supplying a value that is greater than 1, it ends up being exactly 1, and that's why you don't see any change.
     
    OverBoosted and spiney199 like this.
  3. OverBoosted

    OverBoosted

    Joined:
    Sep 10, 2021
    Posts:
    6
    Thanks, I just ended up switching to Vector3.lerp instead.
     
  4. orionsyndrome

    orionsyndrome

    Joined:
    May 4, 2014
    Posts:
    3,096
    Np, btw if you (or someone else) are interested in what the underlying math is
    Vector3.LerpUnclamped is a component-wise variant of this
    Code (csharp):
    1. float lerp(float min, float max, float t) => min * (1f - t) + max * t;
    and Quaternion.Slerp you can find here (along with Vector3.Slerp below it).