The code I have so far lets you click anywhere on a plane and the character will then move and rotate in that direction. What I need help doing is getting it to walk in the direction its facing while rotating until its facing the destination. I think it has to do with rotating at the starting position but I’m not too sure. Below is what I have so far:
using UnityEngine;
using System.Collections;
public class ClickToMove2 : MonoBehaviour {
private Transform myTransform; //this transform
private Vector3 destinationPosition; //destination position
private float destinationDistance; //distance to destination
public float moveSpeed; //controls character move speed
public float rotateSpeed; //speed at which character will rotate
public float tol = 0f;
private Quaternion targetRotation;
// Use this for initialization
void Start () {
myTransform = transform; //set myTransform to this GameObject.Transform
destinationPosition = myTransform.position; //prevents reset of myTransform
}
// Update is called once per frame
void Update () {
destinationDistance = Vector3.Distance(destinationPosition, myTransform.position); //keep track of GameObject and destinationPosition (distance between)
if(destinationDistance < 1f) //prevents shaking behavior
moveSpeed = 0;
else if(destinationDistance > 1f)
moveSpeed = 5.0f;
//will move player if left mouse button was clicked
if (Input.GetMouseButtonDown(0)&& GUIUtility.hotControl ==0) {
Plane playerPlane = new Plane(Vector3.up, myTransform.position);
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
float hitdist = 0.0f;
if (playerPlane.Raycast(ray, out hitdist)) {
Vector3 targetPoint = ray.GetPoint(hitdist);
destinationPosition = ray.GetPoint(hitdist);
targetRotation = Quaternion.LookRotation(targetPoint - transform.position);
}//end nested if
Debug.Log ("CLICKED!");
}//end if
//below will prevent code from running if not needed
myTransform.rotation = Quaternion.RotateTowards(myTransform.rotation, targetRotation, rotateSpeed * Time.deltaTime);
if(destinationDistance > tol){
myTransform.position = Vector3.Lerp(myTransform.position, destinationPosition, 0.2f * Time.deltaTime); //lerp for slowing down movement 0.8f
}//end if
}//end update
}//end ClickToMove2