1. 程式人生 > >Unity 控制攝像機旋轉、放大、縮小

Unity 控制攝像機旋轉、放大、縮小

// Copyright (c) 2014 Gold Experience Team
//
// Elementals version: 1.1.1
// Author: Gold Experience TeamDev (http://www.ge-team.com/)
// Support: [email protected]
// Please direct any bugs/comments/suggestions to [email protected]
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

/*
TERMS OF USE - EASING EQUATIONS#
Open source under the BSD License.
Copyright (c)2001 Robert Penner
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
Neither the name of the author nor the names of contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

#region Namespaces

using UnityEngine;
using System.Collections;

#endregion

/**************
* Orbit Camera event handler.
* It should be attached with Main Camera in Volcanic Rock in Demo scene.
**************/

public class OrbitCamera : MonoBehaviour
{
  #region Variables

	// Target to look at
	public Transform TargetLookAt;
 
	// Camera distance variables
	public float Distance = 10.0f;
	public float DistanceMin = 5.0f;
	public float DistanceMax = 15.0f;  
	float startingDistance = 0.0f;
	float desiredDistance = 0.0f;

	// Mouse variables
	float mouseX = 0.0f;
	float mouseY = 0.0f;
	public float X_MouseSensitivity = 5.0f;
	public float Y_MouseSensitivity = 5.0f;
	public float MouseWheelSensitivity = 5.0f;

	// Axis limit variables
	public float Y_MinLimit = 15.0f;
	public float Y_MaxLimit = 70.0f;   
	public float DistanceSmooth = 0.025f;
	float velocityDistance = 0.0f; 
	Vector3 desiredPosition = Vector3.zero;   
	public float X_Smooth = 0.05f;
	public float Y_Smooth = 0.1f;

	// Velocity variables
	float velX = 0.0f;
	float velY = 0.0f;
	float velZ = 0.0f;
	Vector3 position = Vector3.zero;

  #endregion

  // ######################################################################
  // MonoBehaviour Functions
  // ######################################################################

  #region Component Segments

	void Start() 
	{
        //Distance = Mathf.Clamp(Distance, DistanceMin, DistanceMax);
        //position = transform.position;//add by 張宜龍
        Distance = Vector3.Distance(TargetLookAt.transform.position, gameObject.transform.position);
		if (Distance > DistanceMax)
		  DistanceMax = Distance;
		startingDistance = Distance;
		Reset();
	}

	// Update is called once per frame
	void Update()
	{
	}

	// LateUpdate is called after all Update functions have been called.
	void LateUpdate()
	{
		if (TargetLookAt == null)
		   return;
 
		HandlePlayerInput();
 
		CalculateDesiredPosition();//計算預期位置
 
		UpdatePosition();
	}

  #endregion

  // ######################################################################
  // Player Input Functions
  // ######################################################################

  #region Component Segments

	void HandlePlayerInput()
	{
		// mousewheel deadZone
		float deadZone = 0.01f; 
 
		if (Input.GetMouseButton(0))
		{
		   mouseX += Input.GetAxis("Mouse X") * X_MouseSensitivity;
		   mouseY -= Input.GetAxis("Mouse Y") * Y_MouseSensitivity;
		}
	 
		// this is where the mouseY is limited - Helper script
		mouseY = ClampAngle(mouseY, Y_MinLimit, Y_MaxLimit);
 
		// get Mouse Wheel Input
		if (Input.GetAxis("Mouse ScrollWheel") < -deadZone || Input.GetAxis("Mouse ScrollWheel") > deadZone)
		{
		   desiredDistance = Mathf.Clamp(Distance - (Input.GetAxis("Mouse ScrollWheel") * MouseWheelSensitivity), 
													 DistanceMin, DistanceMax);
		}

        if (Input.GetMouseButton(1))
        {
            Reset();
        }
    }

  #endregion

  // ######################################################################
  // Calculation Functions
  // ######################################################################

  #region Component Segments

	void CalculateDesiredPosition()
	{
		// Evaluate distance
		Distance = Mathf.SmoothDamp(Distance, desiredDistance, ref velocityDistance, DistanceSmooth);
 
		// Calculate desired position -> Note : mouse inputs reversed to align to WorldSpace Axis
		desiredPosition = CalculatePosition(mouseY, mouseX, Distance);
	}

	Vector3 CalculatePosition(float rotationX, float rotationY, float distance)
	{
		Vector3 direction = new Vector3(0, 0, -distance);
		Quaternion rotation = Quaternion.Euler(rotationX, rotationY + 178, 0);
		return  TargetLookAt.position + (rotation * direction);
	}

  #endregion

  // ######################################################################
  // Utilities Functions
  // ######################################################################

  #region Component Segments

	// update camera position
	void UpdatePosition()
	{
		float posX = Mathf.SmoothDamp(position.x, desiredPosition.x, ref velX, X_Smooth);
		float posY = Mathf.SmoothDamp(position.y, desiredPosition.y, ref velY, Y_Smooth);
		float posZ = Mathf.SmoothDamp(position.z, desiredPosition.z, ref velZ, X_Smooth);
		position = new Vector3(posX, posY, posZ);
 
		transform.position = position;
 
		transform.LookAt(TargetLookAt);
	}

	// Reset Mouse variables
	void Reset() 
	{
		mouseX = 0;
		mouseY = 0;
		Distance = startingDistance;
		desiredDistance = Distance;
	}

	// Clamps angle between a minimum float and maximum float value
	float ClampAngle(float angle, float min, float max)
	{
		while (angle < -360.0f || angle > 360.0f)
		{
		   if (angle < -360.0f)
			 angle += 360.0f;
		   if (angle > 360.0f)
			 angle -= 360.0f;
		}
 
		return Mathf.Clamp(angle, min, max);
	}

  #endregion
}

相關推薦

Unity 控制攝像機旋轉放大縮小

// Copyright (c) 2014 Gold Experience Team // // Elementals version: 1.1.1 // Author: Gold Experience TeamDev (http://www.ge-team.com/) /

Unity 模型在移動端進行移動旋轉放大縮小

using System.Collections; using System.Collections.Generic; using UnityEngine; public class RotateControl : MonoBehaviour { //float xSpeed = 100f

Unity攝像機跟隨 Touch遮蔽UI 觸控控制攝像機旋轉,手勢控制放大縮小 穿牆拉近攝像機

using UnityEngine; using System.Collections; using UnityEngine.EventSystems; using UnityEngine.UI; using UnityEngine.PostProcessing; using

WebBrowser控制元件頁面內容放大縮小功能實現

在開發Winform程式中的WebBrowser控制元件時想要實現頁面內容放大、縮小功能,由於IE版本問題,WebBrowser中沒有Ctrl+滾輪實現放大、縮小頁面內容的功能,只能自己實現了。 實現具體程式碼如下: 1。在引用中引用COM元件Microsoft Inte

CSS3 動畫-- 滑鼠移上去,div 會旋轉放大移動

原碼:   <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title>

WPF技術觸屏上的應用系列(五): 圖片列表非同步載入手指進行縮小放大拖動 慣性滑入滑出等效果

        去年某客戶單位要做個大屏觸屏應用,要對檔案資源進行展示之用。客戶端是Window7作業系統,54寸大屏電腦電視一體機。要求有很炫的展示效果,要有一定的視覺衝擊力,可觸控操作。當然滿足客戶的要求也可以有其它途徑。但鑑於咱是搞 .NET技術的,首先其衝想到的微軟

Unity中用觸控控制物體旋轉放大

using UnityEngine; using System.Collections; using System.IO; public class ScaleAndRotate : MonoBehaviour { private Touch oldTouch1; /

CABasicAnimation的基本使用方法(移動·旋轉·放大·縮小

min nts var enum 就是 too 基本 moved ios CABasicAnimation的基本使用方法(移動·旋轉·放大·縮小) CABasicAnimation類的使用方式就是基本的關鍵幀動畫。 所謂關鍵幀動畫,就是將Layer的屬性作為KeyPath來

Unity控制指標旋轉到指定的位置

一、搭建基礎的錶盤、指標 二、編寫控制指標旋轉到指定位置的指令碼: using UnityEngine; using System.Collections; public class Test_OnDashboard : MonoBehaviour { public int

Unity 控制攝像機跟隨運動物體

把以下程式碼繫結到攝像機 using UnityEngine; using System.Collections; public class FollowTarget : MonoBehaviour

vue圖片放大縮小旋轉等。僅需要兩行程式碼!!!

技術參考:https://blog.csdn.net/archer119/article/details/78390203 效果圖 實現步驟: 1.下載Viewer元件       npm install v-viewer --save 2.在

ios實現button變換顏色並可以放大縮小旋轉

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {         

unity 控制物件移動旋轉

W/S :: 前進/後退 A/D :: 下降/上升 滑鼠滾輪 :: 物件移動的速度 游標水平移動 :: 物件左右方向旋轉 游標上下移動 :: 物件上下方向旋轉 using UnityEngine; using System.Coll

C#獲得windows工作列視窗控制代碼及一些操作(放大縮小關閉隱藏……)

需呼叫API函式 需在開頭引入名稱空間using System.Runtime.InteropServices; 1、通過視窗名字查詢 [DllImport("user32.dll", EntryPoint = "FindWindow")] public static extern In

Android 多點觸控(放大縮小旋轉位移)

通過多點觸控實現圖片的放大、縮小、旋轉、位移效果。 private float oldX1 = 0; private float oldX2 = 0; private float oldY1 = 0; private float oldY2 =

cocos2d各種動作的使用(變色跳動旋轉閃爍懸掛放大縮小漸變animation)

跳躍 – CCJumpBy 設定終點位置和跳躍癿高度和次數。 放大到 – CCScaleTo 設定放大倍數,是浮點型。 放大 – CCScaleBy 旋轉到 – CCRotateTo 旋轉 – CCRotateBy 閃爍 – CCBlink

Qt自定義無邊框介面(可放大縮小及拖動)

Qt自定義無邊框介面 使用者介面(User Interface)是指對軟體的人機互動、操作邏輯、介面美觀的整體設計。好的UI設計不僅是讓軟體變得有個性有品味,還要讓軟體的操作變得舒適、簡單、自由、充分體現軟體的定位和特點。很多時候,Qt本地樣式可能無法實現讓我們的介面更簡化、美觀,那麼這

android多框架實現短視訊應用3D手勢旋轉banner控制元件指南針智慧管家等應用原始碼

Android精選原始碼 android智慧管家app原始碼 Android高仿拼多多分類列表 Android百度地圖例項詳解之仿摩拜單車APP RecyclerView的LayoutManager搭建流式佈局 Android自定義View分享——一個圓形

unity編輯器擴充套件#2 GUILayoutEditorGUILayout 控制元件整理

  GUILayout 裝飾類控制元件: GUILayout.FlexibleSpace(); GUILayout.Space(100);//空格,沒什麼好說的 GUILayout.Label("label"); GUILayout.Box(new GUICo

d3滑鼠拖拽放大縮小後動態載入頁面資料demo

d3滑鼠拖拽、放大縮小後動態載入頁面資料demo index.html <!DOCTYPE html> <html> <head>     <meta charset="UTF-8">     <style