- Home /
How do you modify gravity force in this script ?
I followed a tutorial to make the FirstPersonController script and it works quite well, but I'd like to make my character fall faster. I mean it looks like he's jumping on the moon. (I can modify the jump height but not its speed)
By the way if you find faulty things in the script, i'm all ears. Here it is :
using UnityEngine; using System.Collections;
[RequireComponent (typeof(CharacterController))] public class FirstPersonController : MonoBehaviour {
public float movementSpeed = 5.0f;
public float mouseSensitivity = 5.0f;
public float jumpSpeed = 20.0f;
float verticalRotation = 0;
public float upDownRange = 60.0f;
float verticalVelocity = 0;
CharacterController characterController;
// Use this for initialization
void Start () {
Screen.lockCursor = true;
characterController = GetComponent<CharacterController> ();
}
// Update is called once per frame
void Update () {
//Rotation
float rotLeftRight = Input.GetAxis ("Mouse X") * mouseSensitivity;
transform.Rotate (0, rotLeftRight, 0);
verticalRotation -= Input.GetAxis ("Mouse Y") * mouseSensitivity;
verticalRotation = Mathf.Clamp (verticalRotation, -upDownRange, upDownRange);
Camera.main.transform.localRotation = Quaternion.Euler (verticalRotation, 0, 0);
//Movement
float forwardSpeed = Input.GetAxis ("Vertical") * movementSpeed;
float sideSpeed = Input.GetAxis ("Horizontal") * movementSpeed;
verticalVelocity += Physics.gravity.y * Time.deltaTime;
if ( characterController.isGrounded && Input.GetButtonDown ("Jump")) {
verticalVelocity = jumpSpeed;
}
Vector3 speed = new Vector3 ( sideSpeed, verticalVelocity, forwardSpeed );
speed = transform.rotation * speed;
characterController.Move (speed * Time.deltaTime);
}
}
Answer by Dblfstr · Feb 25, 2014 at 03:05 PM
You can access gravity through your Physics settings, or through code. You can also set the scale of gravity on your characters rigidbody in the inspector.
But, this line of code:
verticalVelocity += Physics.gravity.y * Time.deltaTime;
will make the force of gravity very small. Time.DeltaTime is a very small number... milliseconds. So if gravity is -9.8, and you multiply by .01, you get a tiny number. Try adding another multiplier here.
verticalVelocity += Physics.gravity.y * Time.deltaTime * 100f;
Or something like that. You will have to play with it to get it right.
Thanks for your help ! It's almost perfect with Time.deltaTime * 2
, but I'd like it to be 2.5 but it won't work. Why can't I add a decimal number ? (Sorry I'm a real newbie)
You have to add 'f' after a decimal number to indicate that it is a float.
verticalVelocity += Physics.gravity.y * Time.deltaTime * 2.5f;