Slerp rotation of object based on distance from a target object

Hi,

I’m trying to Slerp the rotation of an object (A) as I move it towards a target object (B), until object A’s rotation matches that of B’s when at the same position. I’d like to have this work in reverse also, so that if I then move object A away from B, the rotation moves towards A’s starting rotation. So essentially, I can move A closer to and further away from B and have A’s rotation change based on it’s distance from B. I hope that’s clear :slight_smile:

Any help with this would be great. Thanks

Create two Cubes in Hierarchy.

Rotate randomly Cube1. Move away Cube2.

Drop this code on Cube1:
(use Cube2 as a target)

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class RotateTowards : MonoBehaviour {

    Vector3 initialPosition;
    Quaternion initialRotation;
    public Transform target;

    public float currentDistance;
    private float initialDistance;

	// Use this for initialization
	void Start ()
    {
        initialPosition = transform.position;
        initialRotation = transform.rotation;

        // initial distance between two points
        initialDistance = Vector3.Distance(transform.position, target.position);
    }
	
	// Update is called once per frame
	void Update ()
    {
        // calculate current distance between A and B
        currentDistance = Vector3.Distance(target.position, transform.position);

        // find the ratio between initial dist and current dist between A and B
        float t = currentDistance  / initialDistance;

        // Lerp rotation according to ratio
        transform.rotation = Quaternion.Lerp(target.transform.rotation, initialRotation, t);

        // move towards target
        float step = 1f * Time.deltaTime;
        transform.position = Vector3.MoveTowards(transform.position, target.position, step);
    }
}

Result should look like this: Imgur: The magic of the Internet

Reference: Unity - Scripting API: Quaternion.Lerp