Mouse click move (not follow the cursor!)

Hi,
I’m totally new to Unity and “almost new” to programming in c#, so don’t be mad at my incompetence :slight_smile:
I made this little script to make my character move RTS-like - I click somewhere in the screen, world point gets raycasted and so my object follows the left mouse button. What I want is to make it go to clicked destination on it’s own.

using UnityEngine;
using System.Collections;

public class movement : MonoBehaviour {
	
	public RaycastHit hit;
	public Ray ray;
	public Vector3 direction;
	public float moveSpeed = 0.1f;
	public int rotateSpeed =50;
	private Transform PlayerTransform;
	
	
	
	// Use this for initialization
	void Start () 
	{
		    PlayerTransform = transform;
   		    direction = PlayerTransform.position;
	}
	
	// Update is called once per frame
	void FixedUpdate () 

	{	
	if(Input.GetMouseButton(0))
					
		{
			ray = Camera.main.ScreenPointToRay(Input.mousePosition);
			if(Physics.Raycast (ray, out hit, 100))
			{			
				    Debug.DrawLine (ray.origin, hit.point, Color.red, 2);
					Debug.Log ("Raycast succesful");
					direction = hit.point;
					
					PlayerTransform.position = Vector3.MoveTowards(PlayerTransform.position, hit.point, moveSpeed * Time.deltaTime);
					Debug.DrawLine(PlayerTransform.position, hit.point, Color.blue, 2);
				
					Vector3 targetPoint = hit.point;
        			Quaternion targetRotation = Quaternion.LookRotation(targetPoint - PlayerTransform.position);
        			transform.rotation = Quaternion.Slerp(PlayerTransform.rotation, targetRotation, rotateSpeed * Time.deltaTime);
				targetPoint.y = 0;
			}
			
			
		}
		
	}
}

Thanks in advance.

What I think you are asking for is that the character move to the mouse clicked position even after the mouse button is released. All you have to do to make that happen is to move this line…

PlayerTransform.position = Vector3.MoveTowards(PlayerTransform.position, hit.point, moveSpeed * Time.deltaTime);

…outside the “if(Input.GetMouseButton(0))” if statement. It should execute every frame, not just inside the if. Note you want to use Update() instead of FixedUpdate() for this code.

One more question. How can I make my camera follow my character (using this script).
I found this, but nothing happens with my cam.

using UnityEngine;
using System.Collections;

public class camMove : MonoBehaviour {
	public GameObject target = null;
	public Vector3 positionOffset = Vector3.zero;
	void Start () 
	{
	positionOffset = transform.position + target.transform.position;
	}
	
	// Update is called once per frame
	void Update () 
	{
		if(target != null)
		{
			transform.position = target.transform.position + positionOffset;
		}
	}
}

Also thought about getting my raycasted position to transform my camera…