【Unity3D】摄像机跟随角色移动脚本

2020/02/28
public class CameraController : MonoBehaviour

{

public Camera cam;

public Transform hero;

public bool movable;

public float velocity = 4;

public bool follow;

private Vector3 pivot = new Vector3(0,0,0);

public bool lockCursor = false; //no mouse 1 reqired

public float elevation = 1.5f;

public float sensitivity = 1f;



private float rotationX = 0;

private float rotationY = 190;

public void Start ()

{

if (cam==null) cam = Camera.main;

//if (hero==null) hero = ((CharController)FindObjectOfType(typeof(CharController))).transform;

pivot = cam.transform.position;

}

public void LateUpdate () //updating after hero is moved and all other scene changes made

{

//locking cursor

if (lockCursor)

{

Cursor.lockState = CursorLockMode.Locked;

Cursor.visible = false;

}

else

{

Cursor.lockState = CursorLockMode.None;

Cursor.visible = true;

}

//reading controls

if (Input.GetMouseButton(1) || lockCursor)

{

rotationY += Input.GetAxis("Mouse X")*sensitivity; //note that axises from screen-space to world-space are swept!

rotationX -= Input.GetAxis("Mouse Y")*sensitivity;

rotationX = Mathf.Min(rotationX, 89.9f);

}

//setting cam

if (hero!=null) pivot = hero.position + new Vector3(0, elevation, 0);

//moving

if (movable)

{

if (Input.GetKey (KeyCode.W)) pivot += transform.forward * velocity * Time.deltaTime;

if (Input.GetKey (KeyCode.S)) pivot -= transform.forward * velocity * Time.deltaTime;

if (Input.GetKey (KeyCode.D)) pivot += transform.right * velocity * Time.deltaTime;

if (Input.GetKey (KeyCode.A)) pivot -= transform.right * velocity * Time.deltaTime;

}

cam.transform.localEulerAngles = new Vector3(rotationX, rotationY, 0); //note that this is never smoothed

cam.transform.position = pivot;

}

}

 

(转载本站文章请注明作者和出处 恬静的小魔龙

Show Disqus Comments

Post Directory

扫码或搜索:沉默王二
发送 290992
即可立即永久解锁本站全部文章