标签:unity


Unity中的摄像机跟随,以及人物行走


把这下面的cs文件绑定到摄像机上,然后将目标物体拖动到target就行了

PlayerCameraController.cs


using UnityEngine;
using System.Collections;
public class PlayerCameraController : MonoBehaviour {
public Transform target;
private Vector3 offset;
void Start(){
transform.position = new Vector3 (50.78597f, 9.727137f, -0.187061f);
transform.Rotate (new Vector3 (34.241f, -0.068f, 0));
offset = transform.position - target.position;
}
void Update(){
}
void LateUpdate () {
// 检测是否有目标
if (!target)
return;
if (Input.GetKey (KeyCode.W)) {
target.transform.Translate (Vector3.forward * (2.0f) * Time.deltaTime);
}
if (Input.GetKey (KeyCode.S)) {
target.transform.Translate (Vector3.forward * (-2.0f) * Time.deltaTime);
}
if (Input.GetKey (KeyCode.A)) {
target.transform.Translate (Vector3.left * (2.0f) * Time.deltaTime);
}
if (Input.GetKey (KeyCode.D)) {
target.transform.Translate (Vector3.right * (2.0f) * Time.deltaTime);
}
// transform.position = new Vector3 (50.0f, 9.0f, -3.0f);
// transform.Rotate(new Vector3(38, 0, 0));
// 这两个是设置摄像机的初始位置还有旋转的,有需要可以放进去
transform.position = target.position + offset;
//摄像机总是注视目标
transform.LookAt (target);
}
}