Question by
The-Suspense · Apr 23, 2019 at 08:45 AM ·
cameracharactercharactercontrollercamera-movement
Move Direction Based on camera position not working correctly (3D)
I'm having an issue where My character's movement relative to the camera is wonky. I'm using TransformDirection to move relative to the cameras position. The script works but an issue arises when you consider that the player moves away and toward the camera. this means that if the player is looking down, the character is being pushed forward and into the ground. This causes the character to move slower unless the camera's forward vector is parallel with the ground.
public float speed = 7f;
Vector3 moveDirection;
CharacterController cc;
Camera cam;
private void Awake()
{
cc = GetComponent<CharacterController>();
cam = Camera.main;
}
// Input and non-movement
private void Update()
{
UserInput();
}
// Movement
private void FixedUpdate()
{
Move();
}
private void Move()
{
float time = Time.deltaTime;
moveDirection.Set(moveDirection.x, jumpPos, moveDirection.z);
Gravity();
cc.Move(moveDirection * time);
}
private void UserInput()
{
GetUserInput();
ApplyInputSpeed();
InputMoveDirection(false);
}
void GetUserInput()
{
float horizontal = Input.GetAxis("Horizontal");
float vertical = vertical = Input.GetAxis("Vertical");
moveDirection.Set(horizontal, 0f, vertical);
if (moveDirection.sqrMagnitude > 1f) // Normalizing moveDirection without weird movement
{
moveDirection.Normalize();
}
}
void ApplyInputSpeed()
{
moveDirection.x *= speed;
moveDirection.z *= speed;
}
void InputMoveDirection(bool _canFly)
{
moveDirection = cam.transform.TransformDirection(moveDirection);
if (_canFly == false)
{
moveDirection.y = 0f;
}
}
Comment
Your answer
Follow this Question
Related Questions
having CharacterController movement in fixedupdate causes jerky movement on camera 3 Answers
How can i smooth out my Camera / Player Movement 2 Answers
How to smooth the movement of the camera? 0 Answers
Camera Movement issue 0 Answers
Sit Down First person 0 Answers