- Home /
Question by
DubstepDragon · Jan 04, 2014 at 06:29 PM ·
rotationmovementsmoothdeltatime
Smooth rotation...
My character rotates 90° to the left when the Q key is pressed, and vice versa when the E key is pressed. However, this happens instantly without smooth movement. I saw lots of questions, but they were off-topic. I heard you can do this with "`Time.deltaTime`".
My code is here:
using UnityEngine;
using System.Collections;
public class movement : MonoBehaviour {
public static int speed = 5;
private Vector3 endpos;
private bool moving = false;
void Start () {
endpos = transform.position;
}
void Update () {
if (moving && (transform.position == endpos))
moving = false;
if(!moving && Input.GetKey(KeyCode.W)){
moving = true;
endpos = transform.position + transform.forward;
}
if(!moving && Input.GetKey(KeyCode.A)){
moving = true;
endpos = transform.position - transform.right;
}
if(!moving && Input.GetKey(KeyCode.S)){
moving = true;
endpos = transform.position - transform.forward;
}
if(!moving && Input.GetKey(KeyCode.D)){
moving = true;
endpos = transform.position + transform.right;
}
if(!moving && Input.GetKey(KeyCode.Q)){
moving = true;
transform.Rotate(0,-90,0);
}
if(!moving && Input.GetKey(KeyCode.E)){
moving = true;
transform.Rotate(0,90,0);
}
transform.position = Vector3.MoveTowards(transform.position, endpos, Time.deltaTime * speed);
}
}
Thanks in advance! :D
Comment
Best Answer
Answer by HappyMoo · Jan 04, 2014 at 07:40 PM
using UnityEngine;
using System.Collections;
public class Movement : MonoBehaviour {
public static int speed = 5;
public static int rotspeed = 450;
private Vector3 endpos;
private Quaternion endrot;
private bool moving = false;
void Start () {
endpos = transform.position;
endrot = transform.rotation;
}
void Update () {
if (moving && (transform.position == endpos) && (transform.rotation == endrot))
moving = false;
if(!moving && Input.GetKey(KeyCode.W)){
moving = true;
endpos = transform.position + transform.forward;
}
if(!moving && Input.GetKey(KeyCode.A)){
moving = true;
endpos = transform.position - transform.right;
}
if(!moving && Input.GetKey(KeyCode.S)){
moving = true;
endpos = transform.position - transform.forward;
}
if(!moving && Input.GetKey(KeyCode.D)){
moving = true;
endpos = transform.position + transform.right;
}
if(!moving && Input.GetKeyDown(KeyCode.Q)){
moving = true;
endrot = Quaternion.Euler(0,transform.eulerAngles.y - 90,0);;
}
if(!moving && Input.GetKeyDown(KeyCode.E)){
moving = true;
endrot = Quaternion.Euler(0,transform.eulerAngles.y + 90,0);;
}
transform.position = Vector3.MoveTowards(transform.position, endpos, Time.deltaTime * speed);
transform.rotation = Quaternion.RotateTowards(transform.rotation, endrot, Time.deltaTime * rotspeed);
}
}