unity 摄像头

1、摄像头镜头跟随角色(摄像头位置不变)
参考:http://www.unitymanual.com/5849.html

using UnityEngine;
using System.Collections;

public class ThirdPersonCamera : MonoBehaviour {

    public float distanceAway;          // distance from the back of the craft 
    public float distanceUp;            // distance above the craft 
    public float smooth;                // how smooth the camera movement is 

    private GameObject hovercraft;      // to store the hovercraft 
    private Vector3 targetPosition;     // the position the camera is trying to be in 

    Transform follow;  

    void Start(){  
        follow = GameObject.FindWithTag ("Player").transform;     
    }  

    void LateUpdate ()  
    {  
        // setting the target position to be the correct offset from the hovercraft 
        targetPosition = follow.position + Vector3.up * distanceUp + follow.forward * distanceAway;  
        // making a smooth transition between it's current position and the position it wants to be in 
        transform.position = Vector3.Lerp(transform.position, targetPosition, Time.deltaTime * smooth);  
        // make sure the camera is looking the right way! 
        transform.LookAt(follow);  

    }  
}

2、摄像头锁定角色(摄像头位置跟随角色移动,镜头角度不变)
①在角色物体创建一个空物体,然后把摄像头作为该空物体的子物体。
②在角色绑定脚本中,该空物体的变换位置跟随角色运动改变即可(point.transform.Translate (0, 0, 5*Time.deltaTime);point为空物体,向z轴正方向移动)。

3、摄像头锁定角色,且镜头角度可变。
①在第二种情况的基础上添加。
②摄像头绑定脚本
MouseOrbit.js

var target : Transform;
var distance = 10.0;

var xSpeed = 250.0;
var ySpeed = 120.0;

var yMinLimit = -20;
var yMaxLimit = 80;

private var x = 0.0;
private var y = 0.0;

var isDrog : boolean = false;

@script AddComponentMenu("Camera-Control/Mouse Orbit")

function Start () {
    var angles = transform.eulerAngles;
    x = angles.y;
    y = angles.x;

    // Make the rigid body not change rotation
    //if (rigidbody)
        //rigidbody.freezeRotation = true;
}
//鼠标点击才可进行角度旋转
function OnGUI() {
if(Event.current.type == EventType.MouseDrag) {
isDrog = true;
} else {
isDrog = false;
}
}

function LateUpdate () {
    if (target && isDrog) {
        x += Input.GetAxis("Mouse X") * xSpeed * 0.02;
        y -= Input.GetAxis("Mouse Y") * ySpeed * 0.02;

        y = ClampAngle(y, yMinLimit, yMaxLimit);

        var rotation = Quaternion.Euler(y, x, 0);
        var position = rotation * Vector3(0.0, 0.0, -distance) + target.position;

        transform.rotation = rotation;
        transform.position = position;
    }
}
//旋转角度范围限制
static function ClampAngle (angle : float, min : float, max : float) {
    if (angle < -360)
        angle += 360;
    if (angle > 360)
        angle -= 360;
    return Mathf.Clamp (angle, min, max);
}

你可能感兴趣的:(unity摄像头)