- Home /
Help with elevator Script
Hello! I just need some help with an elevator script. I am truing to make a platform go up, then go back down then back up then back down etc etc. What should I do? Here is my script:
using System.Collections; using System.Collections.Generic; using UnityEngine; public class ElevatorMove : MonoBehaviour { public float speed1 = 100; // Use this for initialization void move () { if (transform.position.y <= 100 ) { transform.Translate (Vector3.up * Time.deltaTime * speed1); } if (transform.position.y >= 100 ) { transform.Translate (Vector3.down * Time.deltaTime * speed1); } } // Update is called once per frame void Update () { move (); } }
Thanks!
Answer by cstooch · Jun 20, 2017 at 04:42 PM
I would structure it like this.. I think this will work:
// declare this and initialize outside your function
Vector3 moveDirection = Vector3.up; // *assuming your platform starts at the bottom
void move ()
{
if (transform.position.y >= 150 )
{
moveDirection = Vector3.down;
}
elseif (transform.position.y <= 50 )
{
moveDirection = Vector3.up;
}
// implicit else... if it's in between, it should keep moving in the same direction it last was...
transform.Translate (moveDirection * Time.deltaTime * speed1);
}
Just to explain my reasoning above.. you start declare/initialize moveDirection before first moving your elevator. This variable will hold the direction the elevator is currently moving. You only need to change this value when the elevator hits the extremes (i.e. the top or bottom).
So if you think through it, first your elevator starts at the bottom, and will rise until it gets to >= 150.. then it will toggle the moveDirection to Vector3.down and stay that way, moving the elevator down, until it gets to the bottom.. in which case moveDirection will switch to Vector3.up.. and we're back to the beginning again... elevator rises... rinse/repeat.
Answer by GamerJoHo · Jun 19, 2017 at 10:24 PM
What's the problem exactly?
I'm assuming the platform doesn't move, or does very very quickly.
You need to change both 100's, to something such as:
void move ()
{
if (transform.position.y <= 150 )
{
transform.Translate (Vector3.up * Time.deltaTime * speed1);
}
if (transform.position.y >= 50 )
{
transform.Translate (Vector3.down * Time.deltaTime * speed1);
}
}
This way it should move between 50 and 150 on the y axis.
The platform goes up just fine, but when it comes back down, it stops, because the second if is true