So I am experimenting with creating a click-to-move script for a simple cube. I can get it to move in the direction of where the cursor is on a plane, which is a good start. However, it maintains the same velocity indefinitely. I am trying to figure out a way to damp the movement so it slows down to a complete stop at where the cursor clicked.
So far my code for the head is such:
Head
using UnityEngine;
using System.Collections;
[RequireComponent (typeof (HeadControl))]
public class Head : MonoBehaviour {
public float moveSpeed = 5;
public Vector3 headVector;
HeadControl control;
Camera viewCamera;
void Awake(){
control = GetComponent<HeadControl> ();
viewCamera = Camera.main;
}
void Update () {
// Movement input
Ray ray = viewCamera.ScreenPointToRay (Input.mousePosition);
Plane groundPlane = new Plane (Vector3.up, 0);
float rayDistance;
if (groundPlane.Raycast (ray, out rayDistance)) {
Vector3 point = ray.GetPoint (rayDistance);
Vector3 destination = new Vector3 (point.x, 0 , point.z);
//print (destination);
headVector = new Vector3 (gameObject.transform.position.x, gameObject.transform.position.y, gameObject.transform.position.z);
Vector3 moveInput = destination - headVector;
Vector3 moveVelocity = moveInput.normalized * moveSpeed;
if (Input.GetMouseButtonDown (0)) {
control.Move (moveVelocity);
}
}
}
}
And the HeadControl Class is written as such:
HeadControl
using UnityEngine;
using System.Collections;
[RequireComponent (typeof(Rigidbody))]
public class HeadControl : MonoBehaviour {
Vector3 velocity;
Rigidbody myRigidbody;
void Start (){
myRigidbody = GetComponent<Rigidbody> ();
}
public void Move (Vector3 _velocity){
velocity = _velocity;
}
void FixedUpdate(){
myRigidbody.MovePosition (myRigidbody.position + velocity * Time.fixedDeltaTime);
}
}
I have been looking into Vector3.SmoothDamp as well as Mathf.Lerp; but I am struggling to figure out how to convert them into a usable syntax for either.
Any help, tips, and advice are very welcome.
Thank you!
P.S. I would also appreciate criticism on how to better format my code.