Changing Direction while Jumping

I have a character currently using the charactercontroller and a self-made script to control it. Everything works fine except that when I press space (to jump) I cannot change direction in air - I either have to be moving in the desired direction before I jump or wait after the jumping is finished. Below I have the parts of my character script that have to do with motion and jumping. It’s in a function Update() loop.

if(controller.isGrounded) 
	{
		movDir = Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
		movDir = transform.TransformDirection(movDir);
		movDir *= groundSpeed;

		if(Input.GetButtonDown("Jump")) {
		movDir.y = jumpHeight; 
		}
	}
	else 
	{		
	//In here is only some script checking whether I'm running or not. . .
	}	
	movDir.y -= gravity * Time.deltaTime;
	
	controller.Move(movDir * Time.deltaTime);
}

I think the code (what seems necessary to show for the problem) is pretty self-explanatory.

You’re only applying input-driven movement if contoller.isGrounded is true. When you jump, you’re no longer grounded (you’re in the air). If you don’t want your controls to only be active while grounded, don’t test for isGrounded before reading/applying those inputs.

Ok, I tried that but then the character controller a) takes a really long time to descend to the ground (the gravity * Time.deltaTime) and when I press jump, it acts as if there is a ceiling just barely above the controller, so it jumps up really fast, but only a really tiny distance before falling back down to the ground rather quickly. Changing the variable for jumpHeight doesn’t do much difference, apart from how high it flings up and drops down (which all happens within a second).

Can you post the code as it looks now? It’s not easy to guess how you have changed it in the meantime.

Ok, this is the “revised” version based on the earlier posts (this one is causing the problems of the imaginary ceiling when pressing the jump button.

function Update()
{
	var controller : CharacterController = GetComponent(CharacterController);
		
		movDir = Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
		movDir = transform.TransformDirection(movDir);
		movDir *= groundSpeed;
		
	if(controller.isGrounded) 
	{
		if(Input.GetButtonDown("Jump")) {
		movDir.y = jumpHeight;
		}
	}
	else 
	{		
		//here is only stuff regulating run speed
	}	
	
	movDir.y -= gravity * Time.deltaTime;
	controller.Move(movDir * Time.deltaTime);
}

Hope this helps the issue.

Oh, I guess I solved it. Instead of those three “movDir =” lines, I scripted:

var inputX = Input.GetAxis("Horizontal");
var inputZ = Input.GetAxis("Vertical");

movDir.x = inputX * groundSpeed;
movDir.z = inputZ * groundSpeed;
movDir = transform.TransformDirection(movDir);

It’s a bit more code, but it works well.

1 Like