Moving Player to a Point Clicked by the Mouse on a Surface


ClickedPointMovement.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
using System.Collections;
using UnityEngine;
 
public class ClickedPointMovement : MonoBehaviour
{
    public float speed = 30;
    RaycastHit hit;
    Camera mainCam;
    Coroutine _MoveCR;
    int layerMask;
 
    void Awake()
    {
        mainCam = Camera.main;
        layerMask = LayerMask.GetMask("Ground");
    }
 
    void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            if (Physics.Raycast(mainCam.ScreenPointToRay(Input.mousePosition), out hit, 100, layerMask))
            {
                if(_MoveCR != null)
                {
                    StopCoroutine(_MoveCR);
                }
                _MoveCR = StartCoroutine(MoveToPosition(hit.point));
            }
        }
    }
 
    IEnumerator MoveToPosition(Vector3 targetPoint)
    {
        targetPoint = new Vector3(targetPoint.x, transform.position.y, targetPoint.z);
        while (Vector3.Distance(transform.position, targetPoint) > 0.01f)
        {
            transform.position = Vector3.MoveTowards(transform.position, targetPoint, speed * Time.deltaTime);
            yield return null;
        }
    }
}