I have been trying to create my own 3rd person camera and character controller, but the forward/backward movement has been bugging me. At first, I had problems with the capsule randomly spinning- so I had to zero out angularVelocity. Not sure if that could have been a factory, but I find it unlikely.
I have this script on my camera, and the camera is a child to the capsule (in order to have camera always follow the character). I want my controls to be left/right to ROTATE the character, and forward/backward to provide actual movement. I honestly don’t remember why I put the character control script on the camera instead of the capsule, I made this late last night and needed a break.
using UnityEngine;
using System.Collections;
public class CharacterControls : MonoBehaviour {
private Player player;
public GameObject person;
public Rigidbody body;
public float rate;
public float runRate;
float run;
public float stopMovementTimer;
public float movementTimeLeft;
public float jumpRate;
public float jumpTimer;
public float jumpTimerLeft;
public float rotateSpeed;
void Start () {
person = transform.parent.gameObject;
body = person.GetComponent<Rigidbody>();
if (GameObject.Find("GameController").GetComponent<Player>() != null)
{
player = GameObject.Find("GameController").GetComponent<Player>();
person.GetComponent<Renderer>().material.color = player.color;
}
else
{
print("ERROR 1: GameController OR Player NOT FOUND!!!");
}
run = 1;
movementTimeLeft = stopMovementTimer;
jumpTimerLeft = 0f;
}
void Update () {
ControlCharacter();
ControlCamera();
}
void ControlCharacter()
{
body.angularVelocity = Vector3.zero;
//Timer Controls
if(jumpTimerLeft > 0)
{
jumpTimerLeft -= Time.deltaTime;
}
if (movementTimeLeft > 0)
{
movementTimeLeft -= Time.deltaTime;
}
//Run Movement
if (Input.GetKey(KeyCode.LeftShift))
{
run = runRate;
} else
{
run = 1f;
}
//Forward and Backward Movement
if (Input.GetKey(KeyCode.W))
{
body.AddForce(gameObject.transform.forward * ( rate * run));
movementTimeLeft = stopMovementTimer;
}
if (Input.GetKey(KeyCode.S))
{
body.AddForce((gameObject.transform.forward * -1) * (rate * run));
movementTimeLeft = stopMovementTimer;
}
//Rotational Movement
if (Input.GetKey(KeyCode.A))
{
body.transform.RotateAround(body.transform.position, body.transform.up, Time.deltaTime * rotateSpeed);
}
if (Input.GetKey(KeyCode.D))
{
body.transform.RotateAround(body.transform.position, body.transform.up, (Time.deltaTime * rotateSpeed) * -1);
}
//Jump
if (Input.GetKeyDown(KeyCode.Space))
{
if (jumpTimerLeft <= 0)
{
body.AddForce(Vector3.up * jumpRate, ForceMode.Impulse);
jumpTimerLeft = jumpTimer;
}
}
//StopMovement
if (movementTimeLeft <= 0)
{
body.velocity = new Vector3(0, body.velocity.y, 0);
}
}
void ControlCamera()
{
transform.LookAt(body.transform);
}
}
(Line 67 if where forward/backward movement occurs)