Unity 進行曲線軌跡自定義,以及根據自定義曲線軌跡運動
1. 當你需要相機鏡頭根據特定軌跡運動。或者一些AI的特定軌跡運動的時候。就可以用到下面的指令碼了
一下方法來自官方案例
直接程式碼嘍。你需要做的就是,複製到你的專案中。拖在指令碼上,你就知道他怎麼用了。
一共兩個指令碼,一個是自定義軌跡的,另一個是使物件根據軌跡運動的。
-
指令碼
WaypointCircuit
。自定義軌跡。把指令碼拖在一個父級上面。然後在子級新增 軌跡物件作為軌跡 頂點。指令碼上的按鍵Assign using all child objects
按下之後。就會把子級物件 作為 曲線的每個頂點。然後生成曲線軌跡運動using System; using System.Collections; using UnityEngine; #if UNITY_EDITOR using UnityEditor; #endif namespace UnityStandardAssets.Utility { public class WaypointCircuit : MonoBehaviour { public WaypointList waypointList = new WaypointList(); [SerializeField] private bool smoothRoute = true; private int numPoints; private Vector3[] points; private float[] distances; public float editorVisualisationSubsteps = 100; public float Length { get; private set; } public Transform[] Waypoints { get { return waypointList.items; } } //this being here will save GC allocs private int p0n; private int p1n; private int p2n; private int p3n; private float i; private Vector3 P0; private Vector3 P1; private Vector3 P2; private Vector3 P3; // Use this for initialization private void Awake() { if (Waypoints.Length > 1) { CachePositionsAndDistances(); } numPoints = Waypoints.Length; } public RoutePoint GetRoutePoint(float dist) { // position and direction Vector3 p1 = GetRoutePosition(dist); Vector3 p2 = GetRoutePosition(dist + 0.1f); Vector3 delta = p2 - p1; return new RoutePoint(p1, delta.normalized); } public Vector3 GetRoutePosition(float dist) { int point = 0; if (Length == 0) { Length = distances[distances.Length - 1]; } dist = Mathf.Repeat(dist, Length); while (distances[point] < dist) { ++point; } // get nearest two points, ensuring points wrap-around start & end of circuit p1n = ((point - 1) + numPoints)%numPoints; p2n = point; // found point numbers, now find interpolation value between the two middle points i = Mathf.InverseLerp(distances[p1n], distances[p2n], dist); if (smoothRoute) { // smooth catmull-rom calculation between the two relevant points // get indices for the surrounding 2 points, because // four points are required by the catmull-rom function p0n = ((point - 2) + numPoints)%numPoints; p3n = (point + 1)%numPoints; // 2nd point may have been the 'last' point - a dupe of the first, // (to give a value of max track distance instead of zero) // but now it must be wrapped back to zero if that was the case. p2n = p2n%numPoints; P0 = points[p0n]; P1 = points[p1n]; P2 = points[p2n]; P3 = points[p3n]; return CatmullRom(P0, P1, P2, P3, i); } else { // simple linear lerp between the two points: p1n = ((point - 1) + numPoints)%numPoints; p2n = point; return Vector3.Lerp(points[p1n], points[p2n], i); } } private Vector3 CatmullRom(Vector3 p0, Vector3 p1, Vector3 p2, Vector3 p3, float i) { // comments are no use here... it's the catmull-rom equation. // Un-magic this, lord vector! return 0.5f* ((2*p1) + (-p0 + p2)*i + (2*p0 - 5*p1 + 4*p2 - p3)*i*i + (-p0 + 3*p1 - 3*p2 + p3)*i*i*i); } private void CachePositionsAndDistances() { // transfer the position of each point and distances between points to arrays for // speed of lookup at runtime points = new Vector3[Waypoints.Length + 1]; distances = new float[Waypoints.Length + 1]; float accumulateDistance = 0; for (int i = 0; i < points.Length; ++i) { var t1 = Waypoints[(i)%Waypoints.Length]; var t2 = Waypoints[(i + 1)%Waypoints.Length]; if (t1 != null && t2 != null) { Vector3 p1 = t1.position; Vector3 p2 = t2.position; points[i] = Waypoints[i%Waypoints.Length].position; distances[i] = accumulateDistance; accumulateDistance += (p1 - p2).magnitude; } } } private void OnDrawGizmos() { DrawGizmos(false); } private void OnDrawGizmosSelected() { DrawGizmos(true); } private void DrawGizmos(bool selected) { waypointList.circuit = this; if (Waypoints.Length > 1) { numPoints = Waypoints.Length; CachePositionsAndDistances(); Length = distances[distances.Length - 1]; Gizmos.color = selected ? Color.yellow : new Color(1, 1, 0, 0.5f); Vector3 prev = Waypoints[0].position; if (smoothRoute) { for (float dist = 0; dist < Length; dist += Length/editorVisualisationSubsteps) { Vector3 next = GetRoutePosition(dist + 1); Gizmos.DrawLine(prev, next); prev = next; } Gizmos.DrawLine(prev, Waypoints[0].position); } else { for (int n = 0; n < Waypoints.Length; ++n) { Vector3 next = Waypoints[(n + 1)%Waypoints.Length].position; Gizmos.DrawLine(prev, next); prev = next; } } } } [Serializable] public class WaypointList { public WaypointCircuit circuit; public Transform[] items = new Transform[0]; } public struct RoutePoint { public Vector3 position; public Vector3 direction; public RoutePoint(Vector3 position, Vector3 direction) { this.position = position; this.direction = direction; } } } } namespace UnityStandardAssets.Utility.Inspector { #if UNITY_EDITOR [CustomPropertyDrawer(typeof (WaypointCircuit.WaypointList))] public class WaypointListDrawer : PropertyDrawer { private float lineHeight = 18; private float spacing = 4; public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) { EditorGUI.BeginProperty(position, label, property); float x = position.x; float y = position.y; float inspectorWidth = position.width; // Draw label // Don't make child fields be indented var indent = EditorGUI.indentLevel; EditorGUI.indentLevel = 0; var items = property.FindPropertyRelative("items"); var titles = new string[] {"Transform", "", "", ""}; var props = new string[] {"transform", "^", "v", "-"}; var widths = new float[] {.7f, .1f, .1f, .1f}; float lineHeight = 18; bool changedLength = false; if (items.arraySize > 0) { for (int i = -1; i < items.arraySize; ++i) { var item = items.GetArrayElementAtIndex(i); float rowX = x; for (int n = 0; n < props.Length; ++n) { float w = widths[n]*inspectorWidth; // Calculate rects Rect rect = new Rect(rowX, y, w, lineHeight); rowX += w; if (i == -1) { EditorGUI.LabelField(rect, titles[n]); } else { if (n == 0) { EditorGUI.ObjectField(rect, item.objectReferenceValue, typeof (Transform), true); } else { if (GUI.Button(rect, props[n])) { switch (props[n]) { case "-": items.DeleteArrayElementAtIndex(i); items.DeleteArrayElementAtIndex(i); changedLength = true; break; case "v": if (i > 0) { items.MoveArrayElement(i, i + 1); } break; case "^": if (i < items.arraySize - 1) { items.MoveArrayElement(i, i - 1); } break; } } } } } y += lineHeight + spacing; if (changedLength) { break; } } } else { // add button var addButtonRect = new Rect((x + position.width) - widths[widths.Length - 1]*inspectorWidth, y, widths[widths.Length - 1]*inspectorWidth, lineHeight); if (GUI.Button(addButtonRect, "+")) { items.InsertArrayElementAtIndex(items.arraySize); } y += lineHeight + spacing; } // add all button var addAllButtonRect = new Rect(x, y, inspectorWidth, lineHeight); if (GUI.Button(addAllButtonRect, "Assign using all child objects")) { var circuit = property.FindPropertyRelative("circuit").objectReferenceValue as WaypointCircuit; var children = new Transform[circuit.transform.childCount]; int n = 0; foreach (Transform child in circuit.transform) { children[n++] = child; } Array.Sort(children, new TransformNameComparer()); circuit.waypointList.items = new Transform[children.Length]; for (n = 0; n < children.Length; ++n) { circuit.waypointList.items[n] = children[n]; } } y += lineHeight + spacing; // rename all button var renameButtonRect = new Rect(x, y, inspectorWidth, lineHeight); if (GUI.Button(renameButtonRect, "Auto Rename numerically from this order")) { var circuit = property.FindPropertyRelative("circuit").objectReferenceValue as WaypointCircuit; int n = 0; foreach (Transform child in circuit.waypointList.items) { child.name = "Waypoint " + (n++).ToString("000"); } } y += lineHeight + spacing; // Set indent back to what it was EditorGUI.indentLevel = indent; EditorGUI.EndProperty(); } public override float GetPropertyHeight(SerializedProperty property, GUIContent label) { SerializedProperty items = property.FindPropertyRelative("items"); float lineAndSpace = lineHeight + spacing; return 40 + (items.arraySize*lineAndSpace) + lineAndSpace; } // comparer for check distances in ray cast hits public class TransformNameComparer : IComparer { public int Compare(object x, object y) { return ((Transform) x).name.CompareTo(((Transform) y).name); } } } #endif }
-
指令碼
WaypointProgressTracker
功能是讓Target
物件根據軌跡進行運動。指令碼拖放在一個物件上之後,然後,指定Circuit
為剛才使用的WaypointCircuit
。然後在指定Target
物件。運行遊戲就可以運動了。試試其他引數,來調節一下速度與運動方式。using System; using UnityEngine; namespace UnityStandardAssets.Utility { public class WaypointProgressTracker : MonoBehaviour { // This script can be used with any object that is supposed to follow a // route marked out by waypoints. // This script manages the amount to look ahead along the route, // and keeps track of progress and laps. [SerializeField] private WaypointCircuit circuit; // A reference to the waypoint-based route we should follow [SerializeField] private float lookAheadForTargetOffset = 5; // The offset ahead along the route that the we will aim for [SerializeField] private float lookAheadForTargetFactor = .1f; // A multiplier adding distance ahead along the route to aim for, based on current speed [SerializeField] private float lookAheadForSpeedOffset = 10; // The offset ahead only the route for speed adjustments (applied as the rotation of the waypoint target transform) [SerializeField] private float lookAheadForSpeedFactor = .2f; // A multiplier adding distance ahead along the route for speed adjustments [SerializeField] private ProgressStyle progressStyle = ProgressStyle.SmoothAlongRoute; // whether to update the position smoothly along the route (good for curved paths) or just when we reach each waypoint. [SerializeField] private float pointToPointThreshold = 4; // proximity to waypoint which must be reached to switch target to next waypoint : only used in PointToPoint mode. public enum ProgressStyle { SmoothAlongRoute, PointToPoint, } // these are public, readable by other objects - i.e. for an AI to know where to head! public WaypointCircuit.RoutePoint targetPoint { get; private set; } public WaypointCircuit.RoutePoint speedPoint { get; private set; } public WaypointCircuit.RoutePoint progressPoint { get; private set; } public Transform target; private float progressDistance; // The progress round the route, used in smooth mode. private int progressNum; // the current waypoint number, used in point-to-point mode. private Vector3 lastPosition; // Used to calculate current speed (since we may not have a rigidbody component) private float speed; // current speed of this object (calculated from delta since last frame) // setup script properties private void Start() { // we use a transform to represent the point to aim for, and the point which // is considered for upcoming changes-of-speed. This allows this component // to communicate this information to the AI without requiring further dependencies. // You can manually create a transform and assign it to this component *and* the AI, // then this component will update it, and the AI can read it. if (target == null) { target = new GameObject(name + " Waypoint Target").transform; } Reset(); } // reset the object to sensible values public void Reset() { progressDistance = 0; progressNum = 0; if (progressStyle == ProgressStyle.PointToPoint) { target.position = circuit.Waypoints[progressNum].position; target.rotation = circuit.Waypoints[progressNum].rotation; } } private void Update() { if (progressStyle == ProgressStyle.SmoothAlongRoute) { // determine the position we should currently be aiming for // (this is different to the current progress position, it is a a certain amount ahead along the route) // we use lerp as a simple way of smoothing out the speed over time. if (Time.deltaTime > 0) { speed = Mathf.Lerp(speed, (lastPosition - transform.position).magnitude/Time.deltaTime, Time.deltaTime); } target.position = circuit.GetRoutePoint(progressDistance + lookAheadForTargetOffset + lookAheadForTargetFactor*speed) .position; target.rotation = Quaternion.LookRotation( circuit.GetRoutePoint(progressDistance + lookAheadForSpeedOffset + lookAheadForSpeedFactor*speed) .direction); // get our current progress along the route progressPoint = circuit.GetRoutePoint(progressDistance); Vector3 progressDelta = progressPoint.position - transform.position; if (Vector3.Dot(progressDelta, progressPoint.direction) < 0) { progressDistance += progressDelta.magnitude*0.5f; } lastPosition = transform.position; } else { // point to point mode. Just increase the waypoint if we're close enough: Vector3 targetDelta = target.position - transform.position; if (targetDelta.magnitude < pointToPointThreshold) { progressNum = (progressNum + 1)%circuit.Waypoints.Length; } target.position = circuit.Waypoints[progressNum].position; target.rotation = circuit.Waypoints[progressNum].rotation; // get our current progress along the route progressPoint = circuit.GetRoutePoint(progressDistance); Vector3 progressDelta = progressPoint.position - transform.position; if (Vector3.Dot(progressDelta, progressPoint.direction) < 0) { progressDistance += progressDelta.magnitude; } lastPosition = transform.position; } } private void OnDrawGizmos() { if (Application.isPlaying) { Gizmos.color = Color.green; Gizmos.DrawLine(transform.position, target.position); Gizmos.DrawWireSphere(circuit.GetRoutePosition(progressDistance), 1); Gizmos.color = Color.yellow; Gizmos.DrawLine(target.position, target.position + target.forward); } } } }
Hello ,I am Edwin
首先謝謝大家的支援,其次如果你碰到什麼其他問題的話,歡迎來 我自己的一個 討論群559666429
來(掃掃下面二維碼),大家一起找答案,共同進步。 同時歡迎各大需求商入住,釋出自己的需求,給群內夥伴提供副職,賺取外快。
相關推薦
Unity 進行曲線軌跡自定義,以及根據自定義曲線軌跡運動
1. 當你需要相機鏡頭根據特定軌跡運動。或者一些AI的特定軌跡運動的時候。就可以用到下面的指令碼了 一下方法來自官方案例 直接程式碼嘍。你需要做的就是,複製到你的專案中。拖在指令碼上,你就知道他怎麼用了。 一共兩個指令碼,一個是自定義軌跡的,另一個是使物
audio自定義樣式,控制操作面板的暫停,播放,獲取音訊的時長,以及根據時長進行進度條展示
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>audio例項</title> <script src="./js
Android使用Java程式碼設定selector或drawable,以及使用自定義控制元件方式使用它
鎮樓圖~~! TextView再給個selecotor 這種東西不要太簡單,但是這種東西我不想重複去寫N個Selector ! so~ /** * 獲取Selector * @param normalDraw *
yii2 類似mongoose schema ,對mongodb 進行型別定義,以及強制轉換
安裝完mongodb的外掛,就可以使用mongodb了,但是,在插入和更新mongodb的資訊的時候,active record 會因為沒有型別, 不能對欄位自動的強制轉換型別,下面是強制轉換型別 common\extensions\mongodb\IActiveRec
帶輸出參數的存儲過程的定義,以及在aso.net中調用
生成 host ddd nvm lose 訂單號 name void identity ALTER proc [dbo].[mp_w_RechargePortalPayPal_All] ( @PayPalOrderNo nvarchar(50), --訂單號 @nAcc
前端開發的模塊化和組件化的定義,以及兩者的關系
ima tid 組件 com 分享圖片 log temp 以及 emp 前端開發的模塊化和組件化的定義,以及兩者的關系 模塊化中的模塊一般指的是 Javascript 模塊,比如一個用來格式化時間的模塊 組件則包含了 template、style 和 script,而它的
postgresql 主鍵自增,以及mybaits 逆向生成
com cli reat 包圖 ble rem default cti password 1、postgresql 主鍵自增 表 event start with 設置起始值 CREATE SEQUENCE event_id_seq START WITH 1
設置防火強開機自啟,以及沒有成功的tomcat開機自啟
over 開機自動啟動 systemctl wall ins div 0.10 down com 防火墻 如果你的系統上沒有安裝使用命令安裝 #yum install firewalld //安裝firewalld 防火墻 開啟服務 # systemctl sta
Qt開發 槽函式定義,以及槽函式二次響應多次響應問題
在Qt開發裡面,有一種傳說中的訊號槽機制,有好幾種實現的方法。 為了實現ui和邏輯的解耦,Qt開發可以利用Qt designer來做UI,同時也有一些UI和邏輯函式之間的通訊建立。 例如,要實現button的相應,有下面幾種方法:
JS 自定義sleep以及Ajax 自執行函式
<script src="/static/js/jquery-2.1.1.min.js"></script> <script> function sleep(numberMillis) { var now = new D
mybatis generator 自定義 ,xml 檔名稱和內容自定義,dao名稱自定義
最近在用mybatis generator 生成程式碼的時候,生成的xml檔案 和類檔案 不是自己想要的,於是修改mybatis generator 的原始碼,重寫方法來達到效果,這裡記錄一下,後期如果需要還可以隨便改成自己想要的! 一 修改註釋 &nb
mysql獲取當前表的自增值,以及修改初始自增值
一、查詢表的自增值 SELECT Auto_increment FROM information_schema.TABLES WHERE Table_Schema= 'database' AND table_name= 'tableName' 說明:'data
當結構體遇上巨集定義,以及函式指標的高階寫法(結構體中能用巨集定義一個函式?)
一、結構體中可以定義一般的巨集定義 如: struct aaa { #define STATUS_1 100 #define STATUS_2 200 #define STATUS_3 300 ........ }; 首先
自己試驗在spring的環繞通知裡獲取目標物件的類名和目標方法的引數類名,用於根據自定義註解判斷訪問許可權,有沒有更好的辦法,高手指點一下
public Object doInBusiness(ProceedingJoinPoint pjp) throws Throwable{ Object[] args = pjp.getArgs(); Class[] argsClass = new Class[ar
swift 字體自適應,寬高自適應
true oat turn ont pre pin class lar ret let kScreenWidth = UIScreen.main.bounds.width let kScreenHeight = UIScreen.main.bounds.height
【演算法模板】二叉樹的三種遍歷方式,以及根據兩種遍歷方式建樹
前言:今年九月份的PAT考試就栽在這“兩種遍歷建樹”上了,剛好沒看,剛好考到。作為自己的遺憾,今日碼完,貼在這裡留個紀念,希望能給自己警醒與警鐘。 簡要概括: 1、二叉樹的三種遍歷方式分別是 先序(先根)遍歷PreOrder,中序(中根)遍歷InOrder,後序(後根
抽象類的定義,抽象方法的定義,抽象類的使用原則與相關規定
一、抽象類 定義:在普通類的基礎上擴充了一些抽象方法 。 1. 抽象方法:只宣告而未實現的方法(沒有方法體) 所有抽象方法使用abstract定義。同時抽象方法所在的類也要用abstract定義,表示抽象類。 舉例:定義一個抽象類: 抽象類中沒有具體實
Linux檢視程序id,以及根據程序id檢視佔用的埠,根據埠號檢視佔用的程序
1. 先根據程序名檢視程序id ps aux | grep 程序名(或者ps -ef | grep 程序名) y@ubuntu:~$ ps aux | grep bitcoind y 2708 101 12.1 1611172 48858
微信小程式資料裡面的資料進行 setData賦值,以及向數組裡面新增自定義的物件
首先 , 微信小程式裡面的賦值大家都不陌生 直接 this.setData方法就好。但是我到了數組裡面的物件賦值就出現了錯誤。當時我也很困惑,然後去查了一下。 解決問題: 程式碼如圖所示: 首先定義一個變數接收數組裡面對象的值,要注意符號。 然後再setDa
bootbox自定義dialog、confirm、alert樣式,以及基本設定方法setDefaults中可用引數
<html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-sc