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!
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.
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);
}