- Home /
How to Lerp a position along one axis only?
I am trying to lerp the local z axis position of a character to the local z axis position of a trigger being entered. I am using Mathf.Lerp but it is triggering an error:
void OnTriggerStay(Collider other) {
other.transform.localPosition.z = Mathf.Lerp(other.transform.localPosition.z, transform.localPosition.z, Time.deltaTime * 1);
}
How could I make this work, or is there a better way?
I have had similar problems, and it is always related to parent/child hierarchy. Try to create a gameobjet, place it on the character pivot, and then make the character child of this object. Create an other gameobject, place it on top of the box pivot and then make the box child of this object.
Now try your script with the new "parents" ins$$anonymous$$d of the character and the box, if it works correctly, you have something wrong with your character/box pivot points. Even if it works, I suggest finding the pivot issue and fixing it.
Answer by Dhiru · Feb 06, 2015 at 11:28 AM
you can't set Z value directly. You have to use its positions.
void OnTriggerStay(Collider other) {
other.transform.localPosition = new Vector3(other.transform.localPosition.x, other.transform.localPosition.y, Mathf.Lerp(other.transform.localPosition.z, transform.localPosition.z, Time.deltaTime * 1));
}
Ok this also works, but for some reason the character is not being lerped to the center of the trigger box. The triggers pivot is in the center of the box and the pivot of the character is also at its own center. Yet when entering the trigger from the back the character lerps through the box all the way to the front of it. I would like it to lerp to the center of the trigger (center according to the z axis only).
Never $$anonymous$$d I worked it out. I simply changed localposition to position.
Answer by instruct9r · Feb 06, 2015 at 11:22 AM
It gives error, because on C# you can't access only one axis.
Create a temrorary variable and lerp it, then assign it to the local position.
void OnTriggerStay(Collider other)
{
Vector3 newPosition = other.transform.localPosition;
newPosition.z = Mathf.Lerp(other.transform.localPosition.z, transform.localPosition.z, Time.deltaTime * 1);
other.transform.localPosition = newPosition;
}
Haven't tested it, but i'm pretty much creating new Vector3 and assigning it to the local position (So X and Y) can get from other object. Then i Lerp the Z. Lastly i apply the new vector to the other's local position
Ok this works, but for some reason the character is not being lerped to the center of the trigger box. The triggers pivot is in the center of the box and the pivot of the character is also at its own center. Yet when entering the trigger from the back the character lerps through the box all the way to the front of it. I would like it to lerp to the center of the trigger (center according to the z axis only).