Lynnstrum
Lynnstrum

Reputation: 194

Unity3D Player movement script

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);
    }
}

Upvotes: 4

Views: 38551

Answers (1)

Harry
Harry

Reputation: 5707

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!

Upvotes: 4

Related Questions