- Home /
Modified CharacterController.Move script not working
I took the example script from CharacterController.Move and modified it to fit my needs, but now the jumping isn't gradual and smooth, the player just snaps to the jump height and then falls back down. All I did was add a way for the player to change direction depending on the way its moving, and took everything out of the if(controller.isGrounded) besides the jump functionality, so that I could move and change directions in the air.
public class PlayerController : 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>();
moveDirection = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
moveDirection *= speed;
if (moveDirection.magnitude > 0)
{
Quaternion newRot = Quaternion.LookRotation(moveDirection);
transform.rotation = Quaternion.Slerp(transform.rotation, newRot, Time.deltaTime * 10);
}
if (controller.isGrounded)
{
if (Input.GetButton("Jump")) {
moveDirection.y = jumpSpeed;
}
}
moveDirection.y -= gravity * Time.deltaTime;
controller.Move(moveDirection * Time.deltaTime);
}
}
Answer by Honorsoft · Feb 13, 2018 at 09:33 AM
It looks like it should work, but I am not as familiar with Unity's controller physics yet. Here's a script I posted before that uses physics to jump, maybe experiment:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerJump : MonoBehaviour {
public Rigidbody rb;
[Range (0.0f, 100.0f)]
public float JumpVelocity = 8.0f;
private bool isGrounded = true;
void Start () {
rb = GetComponent<Rigidbody>();
}
void Update () {
if (isGrounded == true) {
if (Input.GetKey(KeyCode.J) || (Input.GetButtonDown ("Jump"))) {
JumpUp ();
}
}
}
void JumpUp () {
Debug.Log(" JUMP " + transform.up * JumpVelocity + "");
rb.AddForce(Vector3.up * JumpVelocity,ForceMode.Acceleration);
// try also ForceMode.Impulse, ForceMode.VelocityChange and ForceMode.Force }
void OnCollisionEnter(Collision other)
{
if (other.gameObject.tag == "Ground") {
Debug.Log("COLLIDE Begin - isGrounded:" + isGrounded + "");
isGrounded = true;
}
}
void OnCollisionExit(Collision other) {
if (other.gameObject.tag == "Ground") {
Debug.Log("COLLIDE End - isGrounded:" + isGrounded + "");
isGrounded = false;
}
}
}
Your answer
Follow this Question
Related Questions
Help please in regards to character controller 0 Answers
Character contoller movement speed varies with device 0 Answers
Character Creeping Backwards 0 Answers