- Home /
How can I change the speed of a character controller on the fly?
Hi, I'm trying to intergrate a Sprint Fuction for the Untiy First Person Controller but I'm slightly baffled because of the way the code is written.
I want to press Left Shift to run faster and when i let go it goes back to normal speed and here's what I've been doing.
I've found the variable "maxForwardSpeed" and it is set as
var maxForwardSpeed : float = 10.0;
And later on in the code I find...
var zAxisEllipseMultiplier : float = (desiredMovementDirection.z > 0 ?
movement.maxForwardSpeed :
movement.maxBackwardsSpeed) /
movement.maxSidewaysSpeed;
So if I'm doing it right could the code be like this?
function Update()
{
if( Input.GetButtonDown( "Sprint" ) )
{
}
}
But I'm stuck from there, I'm new to scripting and I have no Idea what to type into the Scripting Reference, can someone help me please?
Thanks for reading. (This is written in Javascript)
Learn to use the 101010 button to format your code. It will help people answer your questions.
Tried to use it, Just realised it didn't go to good, dang..
Given the lack of info provided, just replace all references to speed in your script with:
Input.Get$$anonymous$$ey($$anonymous$$eyCode.LeftShift) ? sprintSpeed : normalSpeed
That would be the general way of doing what you want. The more complex your script is, the more you have to modify that.
:O Confused on the "? sprintSpeed : normalSpeed" part :P
Thats an inline if statement (http://en.wikipedia.org/wiki/%3F: ).
speed = Input.Get$$anonymous$$ey($$anonymous$$eyCode.LeftShift) ? sprintSpeed : normalSpeed;
means the same as
if (Input.Get$$anonymous$$ey($$anonymous$$eyCode.LeftShift)) {
speed = sprintSpeed;
} else {
speed = normalSpeed;
}
Answer by coastwise · Jul 22, 2011 at 07:26 PM
You could try the following:
var sprintSpeed : float = 15.0;
var normalSpeed : float = 10.0;
var maxForwardSpeed : float = normalSpeed;
function Update() {
if (Input.GetButtonDown("Sprint")) {
maxForwardSpeed = sprintSpeed;
} else {
maxForwardSpeed = normalSpeed;
}
}
Okay thank you, I'll check it out and see if it works.
In their own variables? So you mean.
var sprintSpeed : float = 15.0; or should it be.. var sprintSpeed = 15.0;
And
var normalSpeed : float = 10.0; or should be.. var normalSpeed = 10.0;
If so should I put them at the start of the script with the other Vars?
At the start of the script with the other vars, then in the if statement you can maxForwardSpeed = sprintSpeed
, etc. I edited the code in my answer to show you.
Getting Error "expecting (, found 'Update'." Sorry for late Comment I've been busy