I use the following code for doors. These doors have 0=x 0=y 0=z rotation, but when I turn the door 90 degrees on the y axis, the door doesn’t open. What am I doing wrong?
var door: Transform;
var angleOpen: int;
var angleClose: int;
var speedOpen: int = 1000;
function OnTriggerStay(other:Collider){
if (door.transform.localEulerAngles.y < angleOpen){
door.transform.Rotate(Vector3.up*Time.deltaTime*speedOpen);
}
}
Don’t trust in the values read from localEulerAngles or eulerAngles: there are many XYZ combinations that may be returned by the same rotation, and the “wrong” one may screw your code up. Do the opposite: keep the desired angle in a variable and “rotate” it mathematically, assigning the result to the actual localEulerAngles every frame:
var door: Transform;
var angleOpen: int;
var angleClose: int;
var speedOpen: float = 90; // degrees per second
private var curAngle;
function Start(){
curAngle = angleOpen; // initialize curAngle
door.transform.localEulerAngles = Vector3(0, curAngle, 0);
}
function OnTriggerStay(other:Collider){
// "rotate" curAngle towards angleOpen
curAngle = Mathf.MoveTowards(curAngle, angleOpen, Time.deltaTime * speedOpen);
// assign it to the door transform
door.transform.localEulerAngles = Vector3(0, curAngle, 0);
}