- Home /
C# Jumping Issue
I've created a basic script for a 3rd person character controller and it works perfectly except for one issue with jumping. No matter what I set the jumpSpeed variable to, the character jumps only about .2 in the y axis.
Here's the code:
using UnityEngine; using System.Collections;
public class SpartanController : MonoBehaviour {
public int horizontalSpeed = 1;
public int verticalSpeed = 1;
public int rotationSpeed = 20;
public int jumpSpeed = 100;
public float gravity = 14.0F;
private Vector3 moveDirection = Vector3.forward;
private CharacterController controller;
void Update()
{
controller = gameObject.GetComponent<CharacterController>();
if (controller.isGrounded)
{
// fully control character
float horizontalDirection = Input.GetAxis("Horizontal") * horizontalSpeed;
float forwardDirection = Input.GetAxis("Vertical") * verticalSpeed;
moveDirection = new Vector3(horizontalDirection, 0, forwardDirection);
// get jump event
if (Input.GetButton("Jump"))
{
moveDirection.y = jumpSpeed;
}
}
else
{
// less control over character, gravity applied
float horizontalDirection = Input.GetAxis("Horizontal") * horizontalSpeed / 2;
float forwardDirection = Input.GetAxis("Vertical") * verticalSpeed / 2;
moveDirection = new Vector3(horizontalDirection, moveDirection.y, forwardDirection);
moveDirection.y -= gravity * Time.deltaTime;
}
moveDirection *= Time.deltaTime;
if (moveDirection.magnitude > 0.05)
{
transform.LookAt(transform.position + new Vector3(moveDirection.x, 0, moveDirection.z));
}
controller.Move(moveDirection);
}
}
Answer by aldonaletto · Dec 30, 2011 at 04:32 AM
I suspect the problem is this line:
moveDirection *= Time.deltaTime;
It's killing the vertical speed in a few updates. Eliminate this line and multiply moveDirection by Time.deltaTime inside Move:
// multiply by Time.deltaTime here:
controller.Move(moveDirection * Time.deltaTime);
Your answer
Follow this Question
Related Questions
Gravity and Jumping for a Character Controller 1 Answer
Let Character Controller jump. 0 Answers
Let Character Controller jump. 1 Answer
How to fix a infinity jump? 1 Answer
Custom Character Script Allowing Movement in the Air? 0 Answers