Problem with movement speed script

Basically, press jump, slowly “transform.up” until you reach max speed, then no more acceleration. Let go of jump and you start over.

problem is, if you ever do hit max speed, it breaks.

why?

var maxFlyingSpeed = 39.75;
var speedIncrement = 0.25;
var currentSpeed = 0.25;


function Update() {
if(currentSpeed >= maxFlyingSpeed){
	speedIncrement = 0.0;
	currentSpeed = maxFlyingSpeed;
	}
if(Input.GetButton("Jump")){ 
	currentSpeed = currentSpeed + speedIncrement;
	rigidbody.velocity = transform.up * -currentSpeed;
	}
	else{
	currentSpeed = 0.1;
	}
}

Try not to modify rigidbody velocity directly, it can get a little wonky. Try something like this:

var maxSpeed = 15.0;
var accel = 5.0;

function FixedUpdate(){
	if(Input.GetButton("Jump")){
		if(rigidbody.velocity.magnitude < maxSpeed){
			rigidbody.AddForce(transform.rotation * Vector3.up * accel);
		}
	}
}

Also make changes to rigidbodies in the fixedupdate rather than the update function.

Taken from first page of Unity Script reference
Update:
This function is called before rendering a frame. This is where most game behaviour code goes, except physics code.
FixedUpdate:
This function is called once every physics time step. This is the place to do physics-based game behaviour.

Whoops! I meant to use FixedUpdate, wrote that off the cuff. Updated it now… (or should I say, FixedUpdated it? :slight_smile: )

hmm ill try the new stuff later on. i found the bug that was causing it to break though.

function Update() {
if(currentSpeed >= maxFlyingSpeed){
speedIncrement = 0.0;
currentSpeed = maxFlyingSpeed;
}

ill play with the settings tomorrow when i wake up. bedtime. lol.

i did notice that the movement that i have for everything is a bit jerky. hmm ill post more code later