Reputation: 11319
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class RotateToTarget : MonoBehaviour
{
public Transform target;
public Transform character;
private const float FAC_SPEED = 10f;
private const float FAC_LERP = 0.9f;
private const float ANG_MAX = 80f;
// Start is called before the first frame update
void Start()
{
/* ... */
}
// Update is called once per frame
void Update()
{
float targetAngleFromForward = Vector3.Angle(character.transform.forward, target.position - transform.position);
Vector3 lerpPoint;
if (targetAngleFromForward < ANG_MAX)
{
// Lerp towards the target's direction
// This is not a very good or elegant solution but it demonstrates the idea
lerpPoint = Vector3.Lerp(transform.forward, (target.position - transform.position).normalized * FAC_SPEED, FAC_LERP * Time.deltaTime);
}
else
{
// Lerp towards the forward direction
// Same idea, but to character.transform.forward instead
lerpPoint = Vector3.Lerp(transform.forward, character.transform.forward * FAC_SPEED, FAC_LERP * Time.deltaTime);
}
transform.rotation = Quaternion.LookRotation(lerpPoint);
}
}
I want to add a global public variable to control the lerpPoint in the IF and in the ELSE. To control the speed of the Lerp towards the target's direction and the Lerp towards the forward direction.
I tried to play with the const variables values but didn't figure it how to control this speeds.
Upvotes: 1
Views: 2989
Reputation: 76
Lerp gives you a single point part of the way between the two inputs, based on the final parameter which should be between 0 and 1. So you need to smoothly increase the final parameter of Lerp from 0 to 1 over time.
Probably the easiest way would be something like this (pseudocode stripping down your example for clarity):
public class RotateToTarget : MonoBehaviour
{
public float secondsToRotate = 2.0f;
private float secondsSoFar = 0.0f;
void Update()
{
secondsSoFar += Time.deltaTime;
float t = secondsSoFar / secondsToRotate;
Vector3 lerpPoint = Vector3.Lerp(start, end, t);
transform.rotation = Quaternion.LookRotation(lerpPoint);
}
}
Upvotes: 2