using System.Collections;
using UnityEngine;
public class PlayerController : MonoBehaviour {
public float speed = 0f;
private Vector3 mousePosition;
private bool moving = false;
void Update () {
Plane plane = new Plane (Vector3.up, transform.position);
Ray ray = UnityEngine.Camera.main.ScreenPointToRay (Input.mousePosition);
float hitPoint = 0.0f;
if (plane.Raycast (ray, out hitPoint)) {
mousePosition = ray.GetPoint(hitPoint);
if (Input.GetMouseButtonDown(0)) {
moving = true;
}
}
Move ();
}
void Move () {
if (moving) {
transform.position = Vector3.MoveTowards(transform.position, mousePosition, speed * Time.deltaTime);
transform.LookAt(mousePosition);
}
}
}
What you have is very close to what you need. Just a slight little change
-
You only want to set a new position when you click
-
You want to move towards it every frame
-
Your moving bool was
[SerializeField] float speed = 1;
Vector3 lastClickedMousePosition;
void Start ()
{
lastClickedMousePosition = transform.position;
}
void Update ()
{
ProcessMouseClick();
Move ();
}
// if the mouse is clicked, it sets where you clicked to the lastMousePosition
void ProcessMouseClick ()
{
if (Input.GetMouseButtonDown(0))
{
Plane plane = new Plane (Vector3.up, transform.position);
Ray ray = UnityEngine.Camera.main.ScreenPointToRay (Input.mousePosition);
float hitPoint = 0.0f;
if (plane.Raycast (ray, out hitPoint)) {
lastClickedMousePosition = ray.GetPoint(hitPoint);
}
}
}
//moves towards last clicked mouse position
void Move ()
{
transform.position = Vector3.MoveTowards(transform.position, lastClickedMousePosition, speed * Time.deltaTime);
transform.LookAt(lastClickedMousePosition);
}