- Home /
"Sliding Door" - Lerp object side to side
Hi all, I've been trying for a while now to get this to work. I'm not entirely sure where I went wrong, but here is the script I've made:
public Vector3 offset;
public float smoothing;
int number;
void Start()
{
number = 0;
}
void Update ()
{
if(Input.GetKeyDown(KeyCode.E))
{
DoorSlide();
}
}
void DoorSlide()
{
if (number == 0)
{
transform.position = Vector3.Lerp(transform.position, transform.position + offset, Time.deltaTime * smoothing);
number++;
}
else
{
transform.position = Vector3.Lerp(transform.position, transform.position - offset, Time.deltaTime * smoothing);
number--;
}
}
I'm setting it up so I can open and close the door by pressing E. I'd like the door to "slide" from it's current position (either open or closed) to its other position.
The difficulty I'm having is that the door opens and closes with the above script, but it snaps from its initial position to its final position. There is no lerping happening.
Any and all suggestions are welcome, and thank you in advance for your time!
Answer by brad_penbach · Mar 02, 2020 at 01:16 AM
I'm going to answer this 6 years later for anybody whose curious - the reason is because lerps need to be done in a while lerp to continually move. Drop it in an IENumerator and have a float for howlong you want it to go for.
while (elapsedTime < howlong)
{
transform.position = Vector3.Lerp(start, des, elapsedTime);
elapsedTime += Time.deltaTime;
yield return null;
}
Answer by Habitablaba · Oct 30, 2014 at 08:01 AM
The key press after you add one to 'number' you subtract one since it is no longer 0.
Try adding a flag for if the door is sliding open or closed, and adding or subtracting accordingly.
Also you modify number, but use offset to move the object. That won't work.
Sorry Habitablaba, but I don't quite understand your answer. I'm still relatively new to coding, so some of this is quite confusing to me. I've re-written my question to be less ambiguous as to what exactly I'm trying to achieve.
Your answer
Follow this Question
Related Questions
Closing sliding door Raycasting 1 Answer
Call a variable from each game object in an array? 1 Answer
Moving player in an arc, from startPoint to endPoint 2 Answers
Make Lerp or other more fluid or continuous 3 Answers
Collision.contacts? 1 Answer