- Home /
moving player relative to camera.
I have a character controller and i am moving it with the fpswalker script:
moveDirection = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
moveDirection = transform.TransformDirection(moveDirection);
moveDirection *= speed;
I have made my game to have a camera looking from above, and i want to have the player move the correct way whaever the camera rotation is.
I mean if i press the up key, i want him moving up from the camera's point of view.
Could you help me understand how to change the code above to have it move the way i want?
Thanks!
Answer by Jaap Kreijkamp · Nov 30, 2009 at 12:29 AM
EDIT bugfixed the normalized.
A (simplified) excerpt from code how I do it (C#):
// we need some axis derived from camera but aligned with floor plane Vector3 forward = cameraTransform.TransformDirection(Vector3.forward); forward.y = 0f; forward = forward.normalized; Vector3 right = new Vector3(forward.z, 0.0f, -forward.x);
float h = joystick.xaxis; float v = joystick.yaxis;
Vector3 walkDirection = (h right + v forward);
The original code did a .normalized on the walkDirection. The reason you possibly want to normalize is to prevent walking faster when going forward + sideways instead of only forwards (given h == v == 1, length of Vector3(h, 0, v) ~= 1.414, not 1). To prevent this you could add the following:
if (walkDirection.sqrMagnitude > 1f) {
walkDirection = walkDirection.normalized;
}
If you want constant walking speed (so no slow walking when joystick isn't pressed much) replace the 1f
with 0f
.
Thanks! That is working! if (grounded) {
forward = cameram.transform.TransformDirection(Vector3.forward);
forward.y = 0;
forward = forward.normalized;
right = new Vector3(forward.z, 0, -forward.x);
h = Input.GetAxis("Horizontal");
v=Input.GetAxis("Vertical");
moveDirection = (h * right + v * forward).normalized ;
moveDirection *= speed ;
if (Input.GetButton ("Jump")) {
moveDirection.y = jumpSpeed;
}
}
I am using that code in javascript. The only thing is that when i stop pressing a key the player keeps moving for while and then stops. any idea why?
Forget it it was the "moveDirection = (h right + v forward).normalized" line, i should not normalize that. Thanks so much!
pabloruiz55, if this answer worked for you, please click the check-mark below the answer to mark it as the accepted answer.