94 lines
2.9 KiB
C#
94 lines
2.9 KiB
C#
using System.Collections;
|
|
using System.Collections.Generic;
|
|
using UnityEngine;
|
|
|
|
public class PlayerCamera : MonoBehaviour
|
|
{
|
|
private float normalSpeed = 0.0035f;
|
|
private float shiftSpeed = 0.06f;
|
|
private float zoomSpeed = -10.0f;
|
|
private float rotateSpeed = 0.1f;
|
|
|
|
private float maxHeight = 40f;
|
|
private float minHeight = 6f;
|
|
|
|
private Vector2 startMouseP;
|
|
private Vector2 dragMouseP;
|
|
private Vector3 defaultCamPosition;
|
|
|
|
private float speed;
|
|
// Start is called before the first frame update
|
|
void Start()
|
|
{
|
|
defaultCamPosition = transform.position;
|
|
}
|
|
|
|
// Update is called once per frame
|
|
void Update()
|
|
{
|
|
// shift to speed UP
|
|
if (Input.GetKey(KeyCode.LeftShift))
|
|
{
|
|
speed = shiftSpeed;
|
|
zoomSpeed = 20.0f;
|
|
}
|
|
else
|
|
{
|
|
speed = normalSpeed;
|
|
zoomSpeed = 10.0f;
|
|
}
|
|
|
|
// reset camera position
|
|
if (Input.GetKeyDown(KeyCode.R))
|
|
{
|
|
transform.position = defaultCamPosition;
|
|
}
|
|
|
|
float hsp = transform.position.y * speed * Input.GetAxis("Horizontal"); // horizontal movement speed
|
|
float vsp = transform.position.y * speed * Input.GetAxis("Vertical"); // vertical movement speed
|
|
float scrollSp = Mathf.Log(transform.position.y) * -zoomSpeed * Input.GetAxis("Mouse ScrollWheel"); // scroll speed
|
|
|
|
// camera height limit
|
|
if (transform.position.y + scrollSp > maxHeight)
|
|
{
|
|
scrollSp = maxHeight - transform.position.y;
|
|
}
|
|
else if (transform.position.y + scrollSp < minHeight)
|
|
{
|
|
scrollSp = minHeight - transform.position.y;
|
|
}
|
|
|
|
Vector3 verticalMove = new Vector3(0,scrollSp,0); // vertical movement
|
|
Vector3 lateralMove = hsp * transform.right; // lateral movement in global world ignore camera facing
|
|
Vector3 fowardMove = transform.forward; // forward movement in global world ignore camera facing
|
|
fowardMove.y = 0; // ignore y axis
|
|
fowardMove = vsp * fowardMove.normalized; // normalize the vector
|
|
|
|
Vector3 move = verticalMove + lateralMove + fowardMove; // total movement
|
|
transform.position += move; // move the camera
|
|
CameraRotation();
|
|
}
|
|
|
|
void CameraRotation()
|
|
{
|
|
// camera rotation while press middle mousebutton
|
|
if(Input.GetMouseButtonDown(2))
|
|
{
|
|
startMouseP = Input.mousePosition;
|
|
}
|
|
|
|
if (Input.GetMouseButton(2))
|
|
{
|
|
dragMouseP = Input.mousePosition;
|
|
|
|
float dx = (dragMouseP - startMouseP).x * rotateSpeed;
|
|
float dy = (dragMouseP - startMouseP).y * rotateSpeed;
|
|
|
|
transform.rotation *= Quaternion.Euler(new Vector3(0, dx, 0));
|
|
transform.GetChild(0).rotation *= Quaternion.Euler(new Vector3(-dy, 0, 0));
|
|
|
|
startMouseP = dragMouseP;
|
|
}
|
|
}
|
|
}
|