Moving along relative z axis with character controller?

Hi guys,

Essentially what I’m making is a hover-craft of sorts. I’m using both the Horizontal and Vertical axis for both the rotation and the up and down movement, relegating the forward movement to an acceleration button of sorts, in this case I’m going with the space bar. All is hunky-dory, except that there seems to be a problem with my script in that the object will move along the game world’s Z, not its own. I know how to solve this with rigidbody, but I’ve found that using character controller is pretty handy for this game as the physics aren’t exactly realistic. When I use axis for this, it works fine, so the problem appears to be in the Input.GetKey function.

Anyway, here is my script, hopefully someone has an answer for me?

void Update () {
		CharacterController controller = GetComponent<CharacterController>();
		
			//move the object up and down
			moveDirection = new Vector3(0,Input.GetAxis ("Vertical"),0);
			moveDirection = transform.TransformDirection(moveDirection) * speed;
		
			//steer the object left and right
			transform.Rotate(0,Input.GetAxis ("Horizontal") * rotationspeed,0);
		
			//accelerate the object forward
			if(Input.GetKey(KeyCode.Space)) {
				moveDirection = new Vector3(0,0,speed);
		}
			controller.Move(moveDirection * Time.deltaTime);

The InverseTransformDirection function transforms a direction from world space to local space. The TransformDirection function transforms a direction from local space to world space, so the other way around.

So, if your moveDirection is based on the world space, and you want the direction to be in the local space of the character, then you should use InverseTransformDirection.

InverseTransformDirection documentation.

Good luck!