Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Character Controller Problems

I'm following a tutorial on making an fps game but the gravity for the character controller isn't working... any thoughts?


using System.Collections;

using System.Collections.Generic;

using UnityEngine;


public class player_movement : MonoBehaviour

{

//variables

private CharacterController characterController;


private Vector3 moveDir;


public float speed = 5f;

private float gravity = 20f;


public float jumpForce = 10f;

private float verticalVelocity;


void Awake()

{

characterController = GetComponent<CharacterController>();

}


// Update is called once per frame

void Update()

{

ApplyGravity();

MovePlayer();

}


//player movement

void MovePlayer()

{

//movement vector3

moveDir = new Vector3(Input.GetAxis(Axis.HORIZONTAL), 0f, Input.GetAxis(Axis.VERTICAL));


//move direction

moveDir = transform.TransformDirection(moveDir);

moveDir *= speed * Time.deltaTime;


//move player

characterController.Move(moveDir);



}


//gravity

void ApplyGravity()

{

if(characterController.isGrounded)

{

//sets up gravity

verticalVelocity -= gravity * Time.deltaTime;


//jump

PlayerJump();


}


else

{

verticalVelocity -= gravity * Time.deltaTime;

}


//activates gravity

moveDir.y = verticalVelocity * Time.deltaTime;

}


//jumping

void PlayerJump()

{

if(characterController.isGrounded && Input.GetKeyDown(KeyCode.Space))

{

verticalVelocity = jumpForce;

}

}


} //class end

Sign In or Register to comment.