- Home /
Elevator script problem (Java)
Hi all, I am new to Unity! I do lift. When you press E, the elevator should move to the next floor (it works), but when you reach the top floor, the elevator continues engines on. Please help fix it. How to make the elevator did not move further up on reaching an endpoint, even when you press E, and how to achieve smooth motion lift?
Please help me! Thank you!
Here's a script that I wrote (elevator should be located initially in the zero-point coordinates):
var elevator: Transform;
var player: Transform;
private var nextPuch: float = 0.5;
private var eleRate : float = 5.0;
private var curPos: Vector3;
function OnTriggerEnter () {
var GO = elevator;
var GO1 = player;
GO1.transform.parent = GO.transform;
}
function OnTriggerExit () {
var GO = elevator;
var GO1 = player;
GO1.transform.parent = null;
}
function Update () {
curPos = transform.position;
var eleHeight = Vector3(0, 5, 0);
//elevator should be located initially in the zero-point coordinates
var floor01 = Vector3(0, 0, 0);
var floor02 = Vector3(0, 5, 0);
var floor03 = Vector3(0, 10, 0);
var floor04 = Vector3(0, 15, 0);
var floor05 = Vector3(0, 20, 0);
if (curPos != floor01 && Input.GetKey(KeyCode.E) && Time.time > nextPuch) {
elevator.transform.position = curPos + eleHeight;
nextPuch = Time.time + eleRate;
}
else if (curPos != floor02 && Input.GetKey(KeyCode.E) && Time.time > nextPuch) {
elevator.transform.position = curPos + eleHeight;
nextPuch = Time.time + eleRate;
}
else if (curPos != floor03 && Input.GetKey(KeyCode.E) && Time.time > nextPuch) {
elevator.transform.position = curPos + eleHeight;
nextPuch = Time.time + eleRate;
}
else if (curPos != floor04 && Input.GetKey(KeyCode.E) && Time.time > nextPuch) {
elevator.transform.position = curPos + eleHeight;
nextPuch = Time.time + eleRate;
}
else if (curPos != floor05 && Input.GetKey(KeyCode.E) && Time.time > nextPuch) {
elevator.transform.position = curPos;
nextPuch = Time.time + eleRate;
}
return;
}
Answer by armoredpokey · Mar 18, 2012 at 06:00 PM
My best guess is that curPos
may not exactly equal floor05
-- there might be some kind of rounding error. Instead of checking whether curPos != various things, I would check whether it's less than or equal to the different floor values. Also, I would refactor the code so you aren't checking Input & Time 5 times every time the code executes, and only compare the y-position values instead of the entire vector.
So it might look something like this:
if (Time.time > nextPuch && Input.GetKey(KeyCode.E)) {
if (curPos.y <= floor01.y) {
// your logic
} else if (curPos.y <= floor02.y) {
// more logic
}
etc
...
}
return;
Your answer
Follow this Question
Related Questions
Disable GameObject Only Father Not Children 2 Answers
GUI.Box within a Collider 1 Answer
Why is my script still running in other scenes? 1 Answer
Light problems 1 Answer