- Home /
Gravity still being applied with unity CharacterController
I am making fairly simple character controller using Unity's built-in CharacterController. It uses a base class, PhysicsObject, for physics handling and a child class, PlayerController, to handle user input and animation. My approach is very similar, in function, to this 2D platformer controller tutorial. Here is my code:
Physics Object
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PhysicsObject : MonoBehaviour
{
[SerializeField] protected PlayerController playerController;
[SerializeField] protected CharacterController controller;
[Header("Movement")]
[SerializeField] protected float moveSpeed;
[SerializeField] protected Vector3 direction;
[Header("Jumping")]
[SerializeField] protected float jumpForce;
[SerializeField] protected float fallMultiplier;
[SerializeField] protected float lowJumpMultiplier;
[SerializeField] protected bool isGrounded;
[SerializeField] protected float maxDistance;
[Header("Animation")]
[SerializeField] protected Animator animator;
private void Awake()
{
controller = playerController.GetPlayerController();
animator = playerController.GetPlayerAnimator();
isGrounded = false;
}
void FixedUpdate()
{
//Check ground
if (direction.x > controller.minMoveDistance || direction.z > controller.minMoveDistance)
{
isGrounded = Physics.Raycast(transform.position, Vector3.down, maxDistance);
}
//Obtain user input
MoveDirection();
//Apply user input
controller.Move(direction * Time.deltaTime);
}
protected virtual void Animate()
{
}
protected virtual void MoveDirection()
{
}
}
Player Controller
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : PhysicsObject
{
public CharacterController GetPlayerController()
{
return gameObject.GetComponent<CharacterController>();
}
public Animator GetPlayerAnimator()
{
return gameObject.GetComponent<Animator>();
}
protected override void MoveDirection()
{
//Jumping
if (Input.GetKeyDown(KeyCode.Space) && isGrounded)
{
direction.y = jumpForce;
}
else
{
direction.y = 0f;
}
//Movement
direction = new Vector3(Input.GetAxis("Horizontal") * moveSpeed, direction.y, Input.GetAxis("Vertical") * moveSpeed);
}
protected override void Animate()
{
}
}
I am using the Unity-chan model as my player character. As you can see in the PhysicsObject, I am using CharacterController.Move(); to move the character -- however gravity is being applied! I tried attaching the two scripts to another 3d object, a box, and no gravity was applied. However, for some odd reason, when I use Unity-chan as the player character gravity is applied to her. Please, help!
PS: this is my first question: sorry if it's sloppy.