I’m trying to write a simple 1st person character controller that stays on a grid (ie. turning 90 degrees per side keystroke, and moving 2 metres per forward/back keystroke. I’ve come up with the code below, in an attempt to cap each move to 2m. When i use Time.deltaTime, the distance moved fluctuates inconsistently around 2m. When i use Time.fixedDeltaTime, the distance moved is consistent, but is over 2 metres.
using UnityEngine;
using System.Collections;
[RequireComponent (typeof(CharacterController))]
public class FPCSteps : MonoBehaviour {
float temp;
bool isRotating;
int horizontalDirection;
float temp2;
bool isMoving;
int forwardDirection;
CharacterController characterController;
// Use this for initialization
void Start () {
Screen.lockCursor = true;
characterController = GetComponent<CharacterController> ();
}
// Update is called once per frame
void Update () {
if (Input.GetKeyDown (KeyCode.W) && !isMoving) {
isMoving = true;
forwardDirection = 1;
temp2 = 0;
}
if (Input.GetKeyDown (KeyCode.S) && !isMoving) {
isMoving = true;
forwardDirection = -1;
temp2 = 0;
}
if (Input.GetKeyDown (KeyCode.D) && !isRotating) {
isRotating = true;
horizontalDirection = 1;
temp = 0;
}
if (Input.GetKeyDown (KeyCode.A) && !isRotating) {
isRotating = true;
horizontalDirection = -1;
temp = 0;
}
transform.Rotate (Vector3.up * 90 * Time.fixedDeltaTime * horizontalDirection, Space.World);
temp += 90 * Time.fixedDeltaTime;
if (temp >= 90) {
temp = 0;
horizontalDirection = 0;
isRotating = false;
}
Camera cam = Camera.main;
characterController.Move (cam.transform.forward * forwardDirection * 2 * Time.deltaTime);
temp2 += 2 * Time.deltaTime;
if (temp2 >= 2){
temp2 = 0;
forwardDirection = 0;
isMoving = false;
}
}
}
Sorry if there’s something obvious i’ve missed, i’m still very new and clueless about C#. If anyone can help, or point me towards a resource that might help, it would be greatly appreciated!