How can I make a Unreal Engine Example Project third preson player controller?
I have recently moved over from UE4 to Unity and I'm trying to learn how to make a nice third person controller. I am aiming for something similar to inFamous: Second Son or Batman: Arkham Knight kind of controller.
Basically I want the camera to orbit around the player, when the player is not moving (which I have already done) and if the user presses W, A, S or D, the character has to rotate towards the input (if the users presses D the player has to rotate to the right, if he presses A - to the left, W - forward and S - back) and then move forward.
Right now my problem is, that the player moves sideways when I press A or D instead of doing what I previously described.
Also it would be great if the player was moving using it's Rigidbody instead of Transform.
I'd really appreciate your help.
Answer by meat5000 · Mar 11, 2018 at 09:57 AM
You need to make your movement Camera Relative, in that regard, if you control system depends on camera facing direction. You just need to find the angle difference around y axis and compensate for it in the controls.
I could, but I'd encourage you to have a go first.
~
https://docs.unity3d.com/$$anonymous$$anual/VectorCookbook.html
~
~
I'll hint that problems like this are best drawn up on paper.
Ok, so I followed some tutorials and read some documentation and came up with this code:
private void Update()
{
Calculate$$anonymous$$ovement();
}
private void FixedUpdate()
{
playerRigidbody.$$anonymous$$oveRotation(Quaternion.Lerp(transform.rotation, rotation, .25f));
playerRigidbody.$$anonymous$$ovePosition(playerRigidbody.position + movement * Time.fixedDeltaTime);
}
private void Calculate$$anonymous$$ovement()
{
float x = Input.GetAxis("Horizontal");
float z = Input.GetAxis("Vertical");
Vector3 input = new Vector3(x, 0f, z);
Vector3 camForward = playerCamera.transform.forward;
camForward.y = 0f;
Quaternion relative = Quaternion.FromToRotation(Vector3.forward, camForward);
Vector3 look = relative * input;
if (input != Vector3.zero)
{
rotation = Quaternion.LookRotation(look);
movement = transform.forward * speed;
}
else
movement = Vector3.zero;
}
It works, but I want to hear your opinion on it's efficiency. What do you think?
Your answer
![](https://koobas.hobune.stream/wayback/20220612154336im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
How to rotate camera diagonally over players shoulder while still facing towards players direction 0 Answers
Connect controls to Camera angle 0 Answers
Xbox one controller spinning 0 Answers
Unity3D accelerometer camera rotation realistic controls 0 Answers
FPSController Prefab - How can i change the Z position of my camera? 0 Answers