錯誤示范:
一開始把移動的代碼寫到update里去了,發現物體老是掉(總之移動非常不流暢,體驗感很差)
void Update(){Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);if (Physics.Raycast(ray, out RaycastHit hit, Mathf.Infinity, LayerMask.GetMask("Interactables"))){if (Input.GetMouseButton(0)){hit.transform.position=ScreenToWorldPos(Input.mousePosition);}}}public Vector3 ScreenToWorldPos(Vector3 screenPosition){Vector3 targetScreenPos = Camera.main.WorldToScreenPoint(depthReference.position);float depth = targetScreenPos.z;screenPosition.z = depth;Vector3 worldPosition = Camera.main.ScreenToWorldPoint(screenPosition);return worldPosition;}
修改:
把移動的代碼改到協程里更新就能流暢移動了
void Update(){Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);if (Physics.Raycast(ray, out RaycastHit hit, Mathf.Infinity, LayerMask.GetMask("Interactables"))){if (Input.GetMouseButtonDown(0)){StartCoroutine(Move(hit.collider.transform));}}}IEnumerator Move(Transform hitobj){while (true){if (Input.GetMouseButton(0) ){Vector3 targetPosition = ScreenToWorldPos(Input.mousePosition);hitobj.position = targetPosition;}yield return null;}}public Vector3 ScreenToWorldPos(Vector3 screenPosition){Vector3 targetScreenPos = Camera.main.WorldToScreenPoint(depthReference.position);float depth = targetScreenPos.z;screenPosition.z = depth;Vector3 worldPosition = Camera.main.ScreenToWorldPoint(screenPosition);return worldPosition;}
問了一下gpt大概是這個原理,說白了就是鼠標輸入不是逐幀更新的,它一直在更新,update執行速度跟不上,協程的執行速度跟得上(但是我還是沒明白為啥協程比update快,就算update重新啟動,可是執行的代碼都是一樣的,要么就是因為update每次都要重新進行射線檢測拖慢了速度吧)