- Home /
How can I implement a SimpleMove max speed?
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
}
Answer by robertbu · Aug 12, 2013 at 09:16 PM
To get your controller to move at a fixed speed, you want to normalize your dir vector. Below line 22 you would put:
dir.Normalize();
You may only want to fix the speed if the distance is above some threshold. That code would look like:
if (dir.magnitude > someValue)
dir = dir.normalized * someValue;
Perfect! Thanks very much, for anyone else with interest in this answer - I found 5 to be a good value for running speed
Your answer
Follow this Question
Related Questions
Run speed in world-based character controller 0 Answers
Increasing Camera "Bobbing" speed when character is sprinting 1 Answer
How to fix? Character grabbing system 1 Answer
How can I change the speed of a character controller on the fly? 1 Answer
Move() function doesn't work on character controller! 0 Answers