Unity3d相機跟隨/旋轉(zhuǎn)/縮放

using System.Collections;

using System.Collections.Generic;

using UnityEngine;

public class CameraFollowss : MonoBehaviour {

? ? //跟隨目標(biāo)

? ? //先確定相機圍繞哪個物體進(jìn)行旋轉(zhuǎn),縮放,平移;也就是需要確定相機的父物體

? //先寫右鍵旋轉(zhuǎn)(相機),確定相機旋轉(zhuǎn)的速度

? public Transform target;

? //旋轉(zhuǎn)的初始角度

? private float x = 0.0f;

? ? private float y = 0.0f;

? //相機旋轉(zhuǎn)的速率

? private float rSpeed = 10.0f;

? //獲取相機Transform對象

? private Transform cam;

? //相機距離目標(biāo)物體的起始距離(距離設(shè)置為負(fù)值,是因為相機是在目標(biāo)物體的正后方)

? private float distance = -5;

? //相機距離的物體的最近和最遠(yuǎn)距離

? private float minDistance = -1;

? ? private float maxDistance = -30;

? //初始位置

? private float camPostion_x = 0;

? ? private float camPostion_y = 0;

? ? void Awake()

? ? {

? ? ? ? transform.position = target.position;

? ? ? ? transform.rotation = Quaternion.Euler(y, x, 0);

? ? ? ? cam = GameObject.Find("Main Camera").transform;

? ? ? ? cam.localPosition = new Vector3(0, 0, distance);

? ? }

? ? void Update()

? ? {

? ? ? ? if (Input.GetMouseButton(1))

? ? ? ? {

? ? ? //右鍵按下

? ? ? x += Input.GetAxis("Mouse X") * rSpeed;

? ? ? ? ? ? y -= Input.GetAxis("Mouse Y") * rSpeed;

? ? ? ? ? ? x = ClampAngle(x, -360, 360);

? ? ? ? ? ? y = ClampAngle(y, -70, 70);

? ? ? ? ? ? var rotation = Quaternion.Euler(y, x, 0);

? ? ? ? ? ? transform.rotation = rotation;

? ? ? ? }

? ? ? ? else if (Input.GetAxis("Mouse ScrollWheel") != 0)

? ? ? ? {

? ? ? //中鍵滾動縮放

? ? ? distance += Input.GetAxis("Mouse ScrollWheel") * 5;

? ? ? ? ? ? distance = Mathf.Clamp(distance, maxDistance, minDistance);

? ? ? ? ? ? cam.localPosition = new Vector3(camPostion_x, camPostion_y, distance);

? ? ? ? }

? ? //中鍵按下平移

? ? if (Input.GetMouseButton(2))

? ? ? ? {

? ? ? ? ? ? camPostion_x -= Input.GetAxis("Mouse X") * 0.04f;

? ? ? ? ? ? camPostion_y -= Input.GetAxis("Mouse Y") * 0.04f;

? ? ? ? ? ? cam.localPosition = new Vector3(camPostion_x, camPostion_y, distance);

? ? ? ? }

? ? }

? ? static float ClampAngle(float angle, float minAngle, float maxAngle)

? ? {

? ? ? ? if (angle < -360)

? ? ? ? ? ? angle += 360;

? ? ? ? if (angle > 360)

? ? ? ? ? ? angle -= 360;

? ? ? ? return Mathf.Clamp(angle, minAngle, maxAngle);

? ? }

}

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容