- Home /
How to offset an object's rotation using Lerp.
I have 2 objects 'a' and 'b' I want object b to have the same rotation as a, but when I press or hold 'W' i want object b to have a small offset on the X-axis making it seem to tilt forward a bit when moving and when I release the 'W' key it should lerp back to object a' position, but I want it to smoothly tilt using Lerp or Slerp, the only result I get is object b moving in a completely different direction.
husk.transform.rotation = Quaternion.SlerpUnclamped(husk.transform.rotation, huskrot, turnAmount*Time.deltaTime);
if (Input.GetKey(KeyCode.W))
{
this.GetComponent<Rigidbody>().AddForce(transform.forward * Forward_Backward_Speed);
huskrot = new Quaternion(transform.rotation.x + tiltAmount, transform.rotation.y, transform.rotation.z, transform.rotation.w);
}
else
{
huskrot = new Quaternion(transform.rotation.x, transform.rotation.y, transform.rotation.z, transform.rotation.w);
}
Answer by exploringunity · Jun 17, 2020 at 05:53 PM
Hey @rgredhcah,
I think you should add a field to keep track of the object's current rotation and use Mathf.MoveTowards to smooth the rotation. Below is a small, but complete example demonstrating the concept.
Obj B is the child of Obj A, and has the DipWhenMovingForward component attached. I made a simple movement script for Obj A just to demonstrate Obj B's rotation while moving. Here's the code:
KeyboardMovement.cs
using UnityEngine;
public class KeyboardMovement : MonoBehaviour
{
public float moveSpeed = 3.5f;
void Update()
{
var dt = Time.deltaTime;
if (Input.GetKey(KeyCode.W)) { transform.position += transform.forward * moveSpeed * dt; }
if (Input.GetKey(KeyCode.S)) { transform.position += -transform.forward * moveSpeed * dt; }
if (Input.GetKey(KeyCode.D)) { transform.position += transform.right * moveSpeed * dt; }
if (Input.GetKey(KeyCode.A)) { transform.position += -transform.right * moveSpeed * dt; }
}
}
DipWhenMovingForward.cs
using UnityEngine;
public class DipWhenMovingForward : MonoBehaviour
{
public float rotationSpeed = 90f;
public float minRotation = 0f;
public float maxRotation = 15f;
float rotation = 0f;
void Update()
{
var dt = Time.deltaTime;
if (Input.GetKey(KeyCode.W))
{
rotation = Mathf.MoveTowards(rotation, maxRotation, rotationSpeed * dt);
}
else
{
rotation = Mathf.MoveTowards(rotation, minRotation, rotationSpeed * dt);
}
transform.rotation = Quaternion.Euler(rotation, 0f, 0f);
}
}
Hope this helps!