Proper use of Character Controller
I have my character (3D model) having just Character Controller and simple script for movement attached.
public class Movement : MonoBehaviour {
public float speed;
public float turnSpeed;
void Update()
{
transform.Rotate(0,Input.GetAxis("Horizontal") * Time.deltaTime* turnSpeed, 0);
transform.Translate(Vector3.forward* Time.deltaTime * speed);
}
The thing is, the character is falling really slowly down even through the floor (plane) - maybe it's a gravity but it really doesn't look realistic at all (it should be falling faster) and the worse thing, it doesn't collide! I though Character Controller should be used instead of a collider?
Could you please help me with this? What is the proper way of using Character Controller? Shall I use classic Collider insted of the controller?
Thanks in advance :)
Answer by Namey5 · Oct 31, 2016 at 06:06 AM
The character controller component is meant to be used as a movement system as well. In this instance, you are coordinating movement through the transform component, which has no resonance to the movement of the character controller, hence rendering it essentially useless. The character controller component has a variety of built-in functions to handle movement calculations as shown in the Unity Manual.
https://docs.unity3d.com/ScriptReference/CharacterController.Move.html
using UnityEngine;
using System.Collections;
public class ExampleClass : MonoBehaviour {
public float speed = 6.0F;
public float jumpSpeed = 8.0F;
public float gravity = 20.0F;
private Vector3 moveDirection = Vector3.zero;
void Update() {
CharacterController controller = GetComponent<CharacterController>();
if (controller.isGrounded) {
moveDirection = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
moveDirection = transform.TransformDirection(moveDirection);
moveDirection *= speed;
if (Input.GetButton("Jump"))
moveDirection.y = jumpSpeed;
}
moveDirection.y -= gravity * Time.deltaTime;
controller.Move(moveDirection * Time.deltaTime);
}
}
You would however use the transform component to handle rotations, generally speaking.
For future reference,
void Update() { CharacterController controller = GetComponent<CharacterController>(); }
should be called within void Start()
, and set to a member variable.
Answer by RealEfrain12 · Feb 01, 2021 at 04:15 PM
I found an answer to your collision problem I think, and with the collision on the character controller. First you want to set anything you’re colliding with to have a box collider and check the isTrigger option, then inside your player script add.
void OnTriggerEnter(Collider other) { if (other.gameObject.tag == “Enter tag here”) { //write your code here } }