I have always been fond of 2D/3D games like Ragnarok Online, and has previously studied the technique of Mouse Picking. Recently, this method has been applied to create my small game.

To implement the method of tracking the character’s movement along the mouse path, the principle of ray tracing is used. The player projects a ray from the camera to the ground, obtaining the surface normal and the x, y, z coordinates. With this control, players can click on a specific location in the game scene using the mouse, and the character will automatically move to that position.


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;
}
}