how to make a player controller in unity 3d code example
Example 1: first person camera controller unity
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CameraLook : MonoBehaviour
{
public float minX = -60f;
public float maxX = 60f;
public float sensitivity;
public Camera cam;
float rotY = 0f;
float rotX = 0f;
void Start()
{
Cursor.lockState = CursorLockMode.Locked;
Cursor.visible = false;
}
void Update()
{
rotY += Input.GetAxis("Mouse X") * sensitivity;
rotX += Input.GetAxis("Mouse Y") * sensitivity;
rotX = Mathf.Clamp(rotX, minX, maxX);
transform.localEulerAngles = new Vector3(0, rotY, 0);
cam.transform.localEulerAngles = new Vector3(-rotX, 0, 0);
if (Input.GetKeyDown(KeyCode.Escape))
{
Cursor.lockState = CursorLockMode.None;
Cursor.visible = true;
}
if (Cursor.visible && Input.GetMouseButtonDown(1))
{
Cursor.lockState = CursorLockMode.Locked;
Cursor.visible = false;
}
}
}
Example 2: unity 3d character controller
using UnityEngine;
using System.Collections;
public class ExampleClass : MonoBehaviour
{
CharacterController characterController;
public float speed = 6.0f;
public float jumpSpeed = 8.0f;
public float gravity = 20.0f;
private Vector3 moveDirection = Vector3.zero;
void Start()
{
characterController = GetComponent<CharacterController>();
}
void Update()
{
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 3: simple first person camera unioty
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CameraLook : MonoBehaviour
{
public float minX = -60f;
public float maxX = 60f;
public float sensitivity;
public Camera cam;
float rotY = 0f;
float rotX = 0f;
void Start()
{
Cursor.lockState = CursorLockMode.Locked;
Cursor.visible = false;
}
void Update()
{
rotY += Input.GetAxis("Mouse X") * sensitivity;
rotX += Input.GetAxis("Mouse Y") * sensitivity;
rotX = Mathf.Clamp(rotX, minX, maxX);
transform.localEulerAngles = new Vector3(0, rotY, 0);
cam.transform.localEulerAngles = new Vector3(-rotX, 0 0);
if (Input.GetKeyDown(KeyCode.Escape))
{
Cursor.lockState = CursorLockMode.None;
Cursor.visible = true;
}
if (Cursor.visible && Input.GetMouseButtonDown(1))
{
Cursor.lockState = CursorLockMode.Locked;
Cursor.visible = false;
}
}
}