Skip to content

Instantly share code, notes, and snippets.

@haydenjameslee
Last active October 1, 2020 07:32
Show Gist options
  • Save haydenjameslee/37827d7c59aa5fc0b301 to your computer and use it in GitHub Desktop.
Save haydenjameslee/37827d7c59aa5fc0b301 to your computer and use it in GitHub Desktop.
using System;
using System.Collections.Generic;
using UnityEngine;
namespace Assets.Scripts.Helpers
{
public class TransformLerp : MonoBehaviour
{
public float lerpSpeed = 1f;
Vector3 _targetPosition;
Vector3 _currentPosition;
Quaternion _targetRotation;
Quaternion _currentRotation;
Vector3 _targetScale;
Vector3 _currentScale;
void Start()
{
_targetPosition = transform.position;
_currentPosition = _targetPosition;
_targetRotation = transform.rotation;
_currentRotation = _targetRotation;
_targetScale = transform.localScale;
_currentScale = _targetScale;
}
void Update()
{
float distance = Vector3.Distance(_currentPosition, _targetPosition);
float ratio = distance / lerpSpeed;
_currentPosition = Vector3.Lerp(_currentPosition, _targetPosition, ratio);
transform.position = _currentPosition;
_currentRotation = Quaternion.Lerp(_currentRotation, _targetRotation, ratio);
transform.rotation = _currentRotation;
_currentScale = Vector3.Lerp(_currentScale, _targetScale, ratio);
transform.localScale = _currentScale;
}
public void SetPosition(Vector3 position, bool lerp = true)
{
_targetPosition = position;
if (!lerp)
{
_currentPosition = position;
transform.position = position;
}
}
public void SetRotation(Quaternion rotation, bool lerp = true)
{
_targetRotation = rotation;
if (!lerp)
{
_currentRotation = rotation;
transform.rotation = rotation;
}
}
public void SetScale(Vector3 scale, bool lerp = true)
{
_targetScale = scale;
if (!lerp)
{
_currentScale = scale;
transform.localScale = scale ;
}
}
public void StopLerping()
{
_currentPosition = _targetPosition;
transform.position = _targetPosition;
_currentRotation = _targetRotation;
transform.rotation = _targetRotation;
_currentScale = _targetScale;
transform.localScale = _targetScale;
}
void OnDisable()
{
StopLerping();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment