Player movement in unity 3d code example
Example 1: C# player movement script unity
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
CharacterController characterController;
public float jumpSpeed = 8.0f;
public float gravity = 20.0f;
public float speed = 9.0f;
private Vector3 moveDirection = Vector3.zero;
private void Start()
{
characterController = GetComponent<CharacterController>();
}
void Update()
{
var horizontal = Input.GetAxis("Horizontal");
var vertical = Input.GetAxis("Vertical");
transform.Translate(new Vector3(horizontal, 0, vertical) * (speed * Time.deltaTime));
if (characterController.isGrounded)
{
moveDirection = new Vector3(Input.GetAxis("Horizontal"), 0.0f, Input.GetAxis("Vertical"));
moveDirection *= speed;
if (Input.GetButton("Jump"))
{
moveDirection.y = jumpSpeed;
}
}
moveDirection.y -= gravity * Time.deltaTime;
characterController.Move(moveDirection * Time.deltaTime);
}
}
Example 2: 3d movement unity
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class playerMovement : MonoBehaviour {
public float speed = 25.0F;
public float jumpSpeed = 8.0F;
public float gravity = 20.0F;
private Vector3 moveDirection = Vector3.zero;
private float turner;
private float looker;
public float sensitivity = 5;
void Start () {
}
void Update () {
CharacterController controller = GetComponent<CharacterController>();
if (controller.isGrounded) {
moveDirection = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
moveDirection = transform.TransformDirection(moveDirection);
moveDirection *= speed;
if (Input.GetButton("Jump")moveDirection.y = jumpSpeed; } turner = Input.GetAxis ("Mouse X")* sensitivity; looker = -Input.GetAxis ("Mouse Y")* sensitivity; if(turner != 0){