I have a character controller I have cobbled together, and it works relatively well (well enough for what I need) except for when it is parented to another object.
If the controller is parented under another object and that object is rotated the character starts rotating randomly and violently.
This is a particular issue as I have a train system which parents the character under itself to prevent the character from being shoved to the back from the velocity, and needs to be able to go up and down inclines without causing this issue, but I am unsure of what is wrong with it, or how to fix it.
I have been over many different controllers I can find the code for online, and cannot work out what is wrong (mainly due to the others working very differently from mine).
Can anyone here see what is wrong?
/*
* ---- Character Controller: Character Movement ----
*
* To Add:
* Smoother Movement
* Better Collision w/ Movement
* Setup as Static to Save Settings
* */
using UnityEngine;
public class CustomCharacterController : MonoBehaviour
{
public static CustomCharacterController playerController;
public float speed = 6.0f;
public float jumpSpeed = 8.0f;
public float gravity = 20.0f;
private Vector3 moveDirection = Vector3.zero;
void Start()
{
Cursor.lockState = CursorLockMode.Locked;
}
public void DontDestroy()
{
//DontDestroyOnLoad(transform.gameObject);
}
void FixedUpdate()
{
if (!PlayerControl.playerControl.isPaused)
{
if (Input.anyKeyDown)
{
Cursor.lockState = CursorLockMode.Locked;
}
float translation = Input.GetAxis("Mouse Y")/*cInput.GetAxis("KVertical")*/ * speed;
float straffe = Input.GetAxis("Mouse X")/*cInput.GetAxis("KHorizontal")*/ * speed;
translation *= Time.deltaTime;
straffe *= Time.deltaTime;
CharacterController cc = GetComponent<CharacterController>();
Vector3 moveDir = new Vector3(straffe, 0, translation);
moveDir = transform.TransformDirection(moveDir);
//rb.MovePosition(transform.position + moveDir);
//rb.velocity = moveDir * 70;
if(cc.isGrounded)
{
moveDirection = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
moveDirection = transform.TransformDirection(moveDirection);
moveDirection *= speed;
}
if (Input.GetKeyDown(KeyCode.Escape))
{
Cursor.lockState = CursorLockMode.None;
}
if (Input.GetKeyDown(PlayerControl.playerControl.sprintKey))
{
//speed = 10.0f;
}
if (Input.GetKeyUp(PlayerControl.playerControl.sprintKey) || !Input.GetKeyDown(PlayerControl.playerControl.sprintKey))
{
//speed = 6.0f;
}
if (Input.GetKeyDown(KeyCode.Space) && cc.isGrounded)
{
moveDirection.y = jumpSpeed;
}
moveDirection.y -= gravity * Time.deltaTime;
cc.Move(moveDirection * Time.deltaTime);
}
}
}