- Home /
Rigidbody speed based on direction relative to camera
I've gotten the player character to move in the direction of the camera, but when the character is in a different direction, it goes slower, and also is unable to run, except for its normal forward position. I am wondering what I need to look into in order to fix this. I'm sure Im missing some parts for the code, but just dont know where to start for researching, any insight would be appreciated.
Here is the code I currently have for the player and camera
Player Movement:
void Update()
{
//Defining Player Inputs
xInput = Input.GetAxis("Horizontal");
yInput = Input.GetAxis("Vertical");
playerMovement = new Vector3(xInput, 0.0f, yInput);
//Camera position
playerMovement = Camera.main.transform.TransformDirection(playerMovement);
if(playerMovement.sqrMagnitude > 1.0f) {
playerMovement.Normalize();
}
//Running
if(Input.GetButton("Run") && isGrounded && !isCrouched && playerMovement.z > 0.1f) {
walkSpeed = runSpeed;
} else {
walkSpeed = defaultMove;
}
}
void FixedUpdate() {
rb.velocity = new Vector3(playerMovement.x * strafeSpeed, rb.velocity.y, playerMovement.z * walkSpeed);
}
Camera Script:
void LateUpdate() {
CamControl();
}
void CamControl() {
mouseX += Input.GetAxis("Mouse X") * RotationSpeed;
mouseY -= Input.GetAxis("Mouse Y") * RotationSpeed;
mouseY = Mathf.Clamp(mouseY, -35, 60);
transform.LookAt(Target);
if(Input.GetKey(KeyCode.LeftAlt)) {
Target.rotation = Quaternion.Euler(mouseY, mouseX, 0);
} else {
Target.rotation = Quaternion.Euler(mouseY, mouseX, 0);
Player.rotation = Quaternion.Euler(0, mouseX, 0);
}
}
Your answer
![](https://koobas.hobune.stream/wayback/20220613044707im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Unity trail render attached to rigidbody is jittery 0 Answers
Moving a camera with AddFoce, or setting velocity, need help 1 Answer
Moving forward relative to camera with atypical WASD script, cinemachine, rigidbody and boxcollider 0 Answers
How to rotate a Rigidbody without rotating the gameObject? 1 Answer
Character Moving in Elliptical Pattern 0 Answers