Smoothing rotation

Hi all! I found a script that creates smoothing on position changes while tracking the head. How do I change this so that it works with rotation?

Smoothing position script:

// -----JS CODE-----
// @input SceneObject target
// @input vec3 offset
// @input float smoothSpeed = 0.05

var transform = script.getTransform();

if(script.target)
{
var targetTransform = script.target.getTransform();
}
else
{
print(“SmoothFollow.js: Please assign the target”);
}

function onUpdateEvent(eventData)
{
if(script.target)
{
var desiredPosition = targetTransform.getWorldPosition().add(script.offset);
var smoothedPosition = vec3.lerp(transform.getWorldPosition(),desiredPosition, script.smoothSpeed)
transform.setWorldPosition(smoothedPosition);
}
}
var event = script.createEvent(“UpdateEvent”);
event.bind(onUpdateEvent);

It’s really similar, but since rotations are in quaternions, you need to use quat.lerp instead of vec3.lerp, and of course get/set rotations instead of positions.

snap-smooth-rotate.zip (4.6 MB)

//@input SceneObject target
/** @type {SceneObject} */
var target = script.target

//@input SceneObject follower
/** @type {SceneObject} */
var follower = script.follower

//@input vec3 offset
/** @type {vec3} */
var offset = script.offset

//@input float smoothSpeed
/** @type {number} */
var smoothSpeed = script.smoothSpeed


if (!target) {
  return print("SmoothRotate.js: Please assign the target")
}

if (!follower) {
  return print("SmoothRotate.js: Please assign the follower")
}

var followerTransform = follower.getTransform()
var targetTransform = target.getTransform()

function onUpdateEvent(eventData) {
  // TODO add offset
  
  var desiredRotation = targetTransform.getWorldRotation()
  var smoothedRotation = quat.lerp(followerTransform.getWorldRotation(), desiredRotation, script.smoothSpeed)
  followerTransform.setWorldRotation(smoothedRotation)
}

var event = script.createEvent("UpdateEvent")
event.bind(onUpdateEvent)
2 Likes

super thanks! you saved me once again :sparkling_heart: