Why won't my guy move forward/back?

This is the code I got from another question.

var speed : float = 1.0;
var rotateSpeed : float = 3.0;
 
function Update() {
	var controller : CharacterController = GetComponent(CharacterController);
    transform.Rotate(0, Input.GetAxis ("Horizontal") * rotateSpeed, 0);
    if (controller.isGrounded) {
    	// We are grounded, so recalculate
    	// move direction directly from axes
    	moveDirection = Vector3(0,0,Input.GetAxis("Vertical"));
    	moveDirection = transform.TransformDirection(moveDirection);
    	moveDirection *= speed;
    	}
    }

I feel as though I understand it now. I’m slowly learning JavaScript. But I don’t understand why my person won’t move forward/back at all

2 Answers

2

Where do you use moveDirection to set your position? One of the things I dislike about javascript is that it isn’t always obvious what the type of a variable is, but I think you’re going to want to do this:

moveDirection = Vector3(0,0,Input.GetAxis("Vertical")) * speed;
transform.position = moveDirection;

or this:

transform.Translate(Vector3.forward * Input.GetAxis("Vertical")) * speed);

There are various simpler ways to write this, but this should get you moving. If neither of those solutions work, then it may be possible that your “Vertical” axis isn’t setup correctly.

Your first example is about to set the object at position (0,0,1) for the all game. As for the second example, he is about to pass through environment. Note that you also have one parenthesis too many.

Right. There was supposed to be a +transform.position in the first example; typing on a phone is hard. As for the second, well, that's what the asker was doing. Personally, I use ridgidbody.MovePosition when moving rigidbodies around.

Well, he is actually moving a character controller.

(left/right, up/down, forward/backward) left or right, up or down, forward or backward are represented by + or -1 in each case. So when you say moveDirection = Vector3(0,0,Input.GetAxis(“Vertical”)) you are giving it a direction of (0,0,1 or -1) This then translates to a direction relative to world space or in your case relative to the transforms local space because of this line:

moveDirection = transform.TransformDirection(moveDirection);

Try removing that line and you might want Camera.main.transform or maybe nothing at all but I don’t think you want it relative to the person walking.

Try this:

var xAxisMove = Input.GetAxis("Horizontal");
var zAxisMove = Input.GetAxis("Vertical");

moveDirection = Vector3(xAxisMove, 0, zAxisMove) * move_speed;

moveDirection = Camera.main.transform.TransformDirection(moveDirection); // <= Optional part