- Home /
Question by
jeff.fnd · Mar 18, 2014 at 07:59 PM ·
keyboardmouseclickclicktomovesimplemove
Movement on the keyboard and mouse
ello guys I have a problem, I have a script ClickToMove, I would add movement via keyboard, AWSD, but that is on the camera.
The character must always move forward toward the camera.
PLEASE someone help me, below is the script.
using UnityEngine;
using System.Collections;
public class ClickToMove : MonoBehaviour {
CharacterController controller;
private Transform myTransform;
private Vector3 destinationPosition;
private float destinationDistance;
void Awake(){
controller = GetComponent<CharacterController>();
}
void Start () {
myTransform = transform;
destinationPosition = myTransform.position;
animation.Play ("idle");
}
void Update () {
destinationDistance = Vector3.Distance(destinationPosition, myTransform.position);
if (Input.GetMouseButton(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);
Quaternion targetRotation = Quaternion.LookRotation(targetPoint - transform.position);
myTransform.rotation = targetRotation;
}
}
if (destinationDistance > .9f) {
controller.SimpleMove(transform.forward * 20);
animation.Play ("run");
}
else if (destinationDistance <= .9f) {
animation.Play ("idle");
}
}
}
Comment