I’m new on Unity 3d. I wrote a keyboard script like mouse look script for first person character - of course with some help - and it works great . I mean i can freely look up,down,left and right when i press keys I attached.
My problem is I want my character look 30 degrees up during pressing the “q” key. And when I release the key I want my character look at the original rotation. I tried some methods Quaternion.LookAt, transform.Rotate but couldn’t succeed. I’d be happy if someone can help me. Thanks.
You can use a coroutine to do the job. Call the function LookUp below when “q” is pressed, and the camera automatically will go up 30 degrees and stay there while the hey is pressed. When the key is released, the camera returns to the original rotation.
You can add the script below to your camera, or add this code to the script you already had:
var duration: float = 0.5; // duration in seconds
private var lookingUp = false;
function LookUp(){
if (lookingUp) return; // aborts if already looking up
lookingUp = true; // flag indicates it's looking up
var start = transform.localRotation; // save the start rotation...
var dest = Quaternion.Euler(-30, 0, 0) * start; // and calculate the destination
var t: float = 0;
while (t <= 1){
t += Time.deltaTime/duration; // advance t a little step each frame
transform.localRotation = Quaternion.Slerp(start, dest, t); // rotate this little
yield; // return here next frame
}
while (Input.GetKey("q")){ // wait while key pressed...
yield; // return here next frame
}
while (t >= 0){
t -= Time.deltaTime/duration; // t go back to 0 a little step each frame
transform.localRotation = Quaternion.Slerp(start, dest, t); // rotate this little
yield; // return here next frame
}
lookingUp = false; // rotation ended
}
function Update(){
if (Input.GetKeyDown("q")){
LookUp();
}
}