I have a script which allows you to control a player, and jump.
However, I'm trying to make it so the player is constantly moving, and not controllable via WASD keys on the keyboard.
Whenever I try to only use controller.Move()
my Gravity function goes away.
Right now, with this code Gravity works, but WASD is enabled as-well.
My question is: How can I make this code make my player constantly move, and still use gravity?
using UnityEngine;
using System.Collections;
public class PlayerMotor : MonoBehaviour {
public float speed = 6.0F;
public float jumpSpeed = 8.0F;
public float gravity = 20.0F;
private Vector3 moveDirection = Vector3.back;
void Update() {
CharacterController controller = GetComponent<CharacterController>();
if (controller.isGrounded)
{
controller.Move (Vector3.back * Time.deltaTime);
moveDirection = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
moveDirection = transform.TransformDirection(moveDirection);
moveDirection *= speed;
if (Input.GetButton("Jump"))
moveDirection.y = jumpSpeed;
}
moveDirection.y -= gravity * Time.deltaTime;
controller.Move(moveDirection * Time.deltaTime);
}
}
Click on the Player object and, in the Inspector view, scroll down to Add Component. Add a Rigidbody, and then add another component as a Capsule Collider this time. You'll need these components to add physics, and therefore movement, to your Player. Then, right-click in your Scripts folder and Create a new C# Script.
Whenever I try to only use controller.Move() my Gravity function goes away
It is an expected behavior as stated in documentation: https://docs.unity3d.com/ScriptReference/CharacterController.Move.html
moveDirection = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
Instead of getting input from player, specify your own moveDirection
. For example: moveDirection = new Vector3(1, 0, 1);
Take a look at the docs for possible values: https://docs.unity3d.com/ScriptReference/Input.GetAxis.html
A side note: CharacterController controller = GetComponent<CharacterController>();
I know you copy from the docs but GetComponent
every Update is not performance wise. Cache it instead!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With