筆者從小喜歡Ragnarok Online這類2D3D的遊戲, 以前都研究過Mouse Picking這個技術, 最近亦套用此方法製作小遊戲。

要製作角色追踪滑鼠路徑的方法實現玩家對角色的控制原理是光線追蹤(RayTracing), 玩家由Camera投射一條光線指向地面, 得出地面的法線 (Normal)並得出 x, y, z座標位置。在這種控制下,玩家可以通過滑鼠點擊在遊戲場景中指定位置,角色會自動移動到該位置。

以下是實現這種控制的步驟:
-
這個方法是實現角色追踪滑鼠路徑的基本原理,可以適用於各種不同的遊戲場景。需要這個功能可以參考以下代碼。
void UpdatePointerMovement() { // Check if the mouse button is being held down or being pressed if (Input.GetMouseButtonDown(0) || Input.GetMouseButton(0)) { RaycastHit hit; Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); int groundLayer = LayerMask.GetMask("Ground"); // Add a layer mask for the ground layer only if (Physics.Raycast(ray, out hit, Mathf.Infinity, groundLayer)) // Add the layer mask to the raycast function { // Move the player towards the clicked location Debug.DrawRay(ray.origin, ray.direction * hit.distance, Color.yellow, 2); newPos = new Vector3(hit.point.x, 0, hit.point.z); Debug.Log("x=" + newPos.x + " | y=" + newPos.y + " |z=" + newPos.z); } } // Check if the target position is not reached float Dist = Vector3.Distance(transform.position, newPos); Debug.Log(Dist); if ( Dist > pointerDistance) // if the target position has not been reached > pointer distance { // Calculate the movement direction and rotation Vector3 moveDir = Vector3.Lerp(transform.position, newPos, Time.deltaTime * moveSpeed); moveDirection = new Vector3(moveDir.x - transform.position.x, 0.0f, moveDir.z - transform.position.z).normalized; // transform.LookAt(newPos); if (profile.current_Player_State != playerState.FAINT) { // Move the player rb.velocity = moveDirection * moveSpeed; } } else { // Stop movement rb.velocity = Vector3.zero; // Reset target position to the status “not set” newPos = transform.position; } }