I am using the SimpleMove() function to create a click to move character controller and it works fine as long as the user clicks near to the player, but if the player clicks far in the distance then they move very far very quickly. I would like to implement a maximum speed and have tried to create an if statement to limit the value being entered into the SimpleMove() function, but to no avail, any help would be appreciated!
The code is as follows:
var speed: float = 5; // Determines how quickly object moves towards position
private var targetPosition:Vector3; // current target pos
private var character: CharacterController;
function Start(){
character = GetComponent(CharacterController);
targetPosition = transform.position;
}
function Update () {
if(Input.GetKey(KeyCode.Mouse0)){
// create a logical horizontal plane at the player position:
var playerPlane = new Plane(Vector3.up, transform.position);
var ray = Camera.main.ScreenPointToRay (Input.mousePosition);
var hitdist = 0.0;
// find point clicked in the plane (if any):
if (playerPlane.Raycast (ray, hitdist)) {
// update targetPosition to the clicked point:
targetPosition = ray.GetPoint(hitdist);
var dir = targetPosition - transform.position;
dir.y = 0; // keep only the horizontal direction
}
}
// always try to move the character to targetPosition:
character.SimpleMove(dir * speed); // move taking gravity into account
}