Jet-Pack Script

Hey guys,

I am trying to write a script for a jetpack. It should give the character controller the possibility to get up in the air if there’s enough gas. furthermore the gas should increase when the controller is grounded and decrease when the controller is “flying”.

That’s my script: http://hastebin.com/lusafidiqa.coffee

It’s really buggy and I don’t know why. Sometimes at least some of the planned things work. I don’t really get what I am doing wrong. Sry for not asking a specific question but it would be great if someone could check the script and tell me what’s wrong with it. I am new to Unity and try to improve my scripting-skills.

Thanks

moko

You have a serious problem. The code as it is right now will hang Unity. The issue is the while loop on line 26 combined with you declaring gas an integer. So your while loop cycles, increment gas by some small fraction. Bug since gas is an integer, it never increased (stays zero), so the while loop never terminates. And you don’t want a while loop anyway. There are a few more problematic things here as well. For example, you are using CharacterController.Move() and CharacterController.SimpleMove(). You should pick one or the other.

Here is the results of some quick hacking on your code. It could be written better, but it gives you a starting point. If you jump, you will go to the top of the jump height and stay there (flying) until you run out of gas.

#pragma strict

var groundSpeed : float = 5.0;
var airSpeed : float = 10.0;
var jumpSpeed : float = 1.0;
var rotateSpeed : float = 3.0;
var gas : float = 0.0;
var gasStorageRate : float = 2.0;
var gasUseRate : float = 4.0;
var maxGas : float = 300.0;
var gravity : float = 10.0;

private var moveDirection : Vector3 = Vector3.zero;

function Update() {

    var controller : CharacterController = GetComponent(CharacterController);
    
     // Move forward / sideward
	transform.Rotate(0, Input.GetAxis ("Horizontal") * rotateSpeed, 0);
	var y = moveDirection.y;
	if (controller.isGrounded)
    	moveDirection = transform.forward * groundSpeed * Input.GetAxis ("Vertical");
    else
    	moveDirection = transform.forward * airSpeed * Input.GetAxis ("Vertical");
    
    moveDirection.y = y;
    moveDirection.y -= gravity * Time.deltaTime;
        
	if (controller.isGrounded) {
		gas += gasStorageRate * Time.deltaTime;
		if (gas > maxGas) gas = maxGas;
		if (Input.GetButton ("Jump")) {
    		moveDirection.y = jumpSpeed;
    	}
	} 
	else {
		gas -= gasUseRate * Time.deltaTime;
		if (gas < 0.0) gas = 0.0;
		if (gas > 0.0 && moveDirection.y < 0.0)
			moveDirection.y = 0.0;
	}
	
	// Move the controller
	controller.Move(moveDirection * Time.deltaTime);
}

P.S. You will get more eyes looking at your question/code if you past a script into the question instead of using PasteBin. I’d only use PasteBin if your code is much longer than the script you provided.