您的位置:首页 > 移动开发 > Unity3D

Unity3d摄像机跟随角色移动脚本

2017-09-25 23:25 633 查看
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;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: