I want to make a object (fuse) fly towards another object (fuse box) and also adapt its transform.rotation values gradually. (I use transform.position/rotation = Vector3/Quarteronin.Lerp(initial.position/rotation, fuseBox.position/rotation, progressTimer
))
These are the variables, declared outside the shown code:
private Transform closestFuseBoxTransform = null;
private Transform initialFuseTransform = null;
private float fuseSnappingProgress = -1f;
private float fuseSnapingAnimationTime = 100f;
private float fuseSnappingBezierStrength = 1f;
This is my code so far: (placed inside Update()
)
if (Input.GetKeyDown(KeyCode.Space))
{
// Get initial and destination Transforms
closestFuseBoxTransform = GetClosestObject(GameObject.FindGameObjectsWithTag("FuseDst"););
initialFuseTransform = transform;
//if-block gets "turned on"
fuseSnappingProgress = 0f;
Debug.Log(transform.rotation.eulerAngles);
}
if (fuseSnappingProgress >= 0f)
{
// Increment real time timer
fuseSnappingProgress = Time.deltaTime / fuseSnapingAnimationTime;
// Makes transition fancy, works because x^y (y > 0) returns for 0 < x < 1 always 0 < y < 1
float fuseSnappingProgressBezier = Mathf.Pow(fuseSnappingProgress, fuseSnappingBezierStrength);
Debug.Log(fuseSnappingProgressBezier);
// Set the transform values using initial and desired position and just calculated 'fuseSnappingProgressBezier'
transform.position = Vector3.Lerp(initialFuseTransform.position, closestFuseBoxTransform.position,
fuseSnappingProgressBezier);
transform.rotation = Quaternion.Lerp(initialFuseTransform.rotation, closestFuseBoxTransform.rotation,
fuseSnappingProgressBezier);
// When the animation reaches 100%...
if (fuseSnappingProgress >= 1f)
{
// Adjust for potential lag, that caused Time.deltaTime to be huge and make the timer jump past 1
transform.position = closestFuseBoxTransform.position;
transform.rotation = closestFuseBoxTransform.rotation;
//if-block gets "turned off"
fuseSnappingProgress = -1f;
Debug.Log("Fuse snapped into cosest Fuse Box");
}
}
This it what happens in-game: (The animation lasts 100 seconds (as intended) but the fuse already moved to the intended position (gets Infinity closer, but I cant spot the exponentials fot that) after a few seconds)
CodePudding user response:
Your initialFuseTransform
is a Transform which means it is a reference type which means that when you modify your object's transform, it is modifying the initialFuseTransform
aswell. So instead of doing that, have 2 value types like Vector3 initialPosition
and Quaternion initialRotation
and handle your lerping based on these.
For more detail check out microsoft documentation for value vs reference types.