Hi. I am using the CNcontroller plugin, which it comes with the prefabs and the scripts i need. Everything works fine, i have just a problem. Sometimes, the player is moving on the Y. I don’t want that and it shouldn’t do that. What is to do ?
Here’s the script i am using. It comes as an example with the cncontroller prefab. I found it very suitable to my project so i kept it.
using System;
using UnityEngine;
using System.Collections;
[RequireComponent(typeof(CharacterController))]
public class Controller3DExample : MonoBehaviour
{
public const float ROTATE_SPEED = 15f;
public float movementSpeed = 5f;
public CNAbstractController MovementJoystick;
private CharacterController _characterController;
private Transform _mainCameraTransform;
private Transform _transformCache;
private Transform _playerTransform;
void Start()
{
// You can also move the character with an event system
// You MUST CHOOSE one method and use ONLY ONE a frame
// If you wan't the event based control, uncomment this line
// MovementJoystick.JoystickMovedEvent += MoveWithEvent;
_characterController = GetComponent<CharacterController>();
_mainCameraTransform = Camera.main.GetComponent<Transform>();
_transformCache = GetComponent<Transform>();
_playerTransform = _transformCache.FindChild("Cocoon");
}
// Update is called once per frame
void Update()
{
var movement = new Vector3(
MovementJoystick.GetAxis("Horizontal"),
0f,
MovementJoystick.GetAxis("Vertical"));
CommonMovementMethod(movement);
}
private void MoveWithEvent(Vector3 inputMovement)
{
var movement = new Vector3(
inputMovement.x,
0f,
inputMovement.y);
CommonMovementMethod(movement);
}
private void CommonMovementMethod(Vector3 movement)
{
movement = _mainCameraTransform.TransformDirection(movement);
movement.y = 0f;
movement.Normalize();
FaceDirection(movement);
_characterController.Move(movement * movementSpeed * Time.deltaTime);
}
public void FaceDirection(Vector3 direction)
{
StopCoroutine("RotateCoroutine");
StartCoroutine("RotateCoroutine", direction);
}
IEnumerator RotateCoroutine(Vector3 direction)
{
if (direction == Vector3.zero) yield break;
Quaternion lookRotation = Quaternion.LookRotation(direction);
do
{
_playerTransform.rotation = Quaternion.Lerp(_playerTransform.rotation, lookRotation, Time.deltaTime * ROTATE_SPEED);
yield return null;
}
while ((direction - _playerTransform.forward).sqrMagnitude > 5f);
}
}
What to do ? As i said, it only happens sometime. In general, it happens when i want to walk in my front and my right … (diagonal). I am working at a first person view project and i don;t want my player to move on y. Ha ha ha, is so trolling when the player kicks the roof :))