Character facing direction of movement - movement using camera transform?
Hello
This is the code we are using to move the player. The idea being the controls are relative to the cameras position as the camera changes (similar to FEZ fashion).
Problem is now we have this working, we need the players character to face the direction it is moving in. We are currently trying with the movement on the parent object and attempting to rotate the child character object. If that makes sense.
This is the movement script. void Update () {
//Jump
if (Input.GetKeyDown (KeyCode.Space) && (doubleJump < 2)) {
rb.AddForce (new Vector3 (0, 1, 0) * jumpforce);
doubleJump++;
}
//movement
if (Input.GetKey (KeyCode.UpArrow))
{
movement = transform.position += Camera.main.transform.forward * speed;
hammy.transform.LookAt(movement);
}
if (Input.GetKey (KeyCode.DownArrow))
{
movement = transform.position -= Camera.main.transform.forward * speed;
hammy.transform.LookAt(movement);
}
if (Input.GetKey (KeyCode.LeftArrow))
{
movement = transform.position -= Camera.main.transform.right * speed;
hammy.transform.LookAt(movement);
}
if (Input.GetKey (KeyCode.RightArrow))
{
movement = transform.position += Camera.main.transform.right * speed;
hammy.transform.LookAt(movement);
}
This is the camera follow script
void LateUpdate()
{
//Follows the Players Position
parent.transform.position = target.transform.position;
//Lerps and chnages the cameras positon relevent to the Player
transform.position = Vector3.Lerp (transform.position, currentCamera.transform.position, Time.deltaTime * 1.5f);
transform.rotation = Quaternion.Lerp (transform.rotation, currentCamera.transform.rotation, Time.deltaTime * 1.5f);
}
We have spent hours trying to figure this out.
Any help would be greatly appreciated. Thanks
Answer by Salmjak · Feb 16, 2016 at 02:19 PM
the direction can be described as the normalized difference between two points.
Vector3 direction = (target.position - your.position).normalized;
Quaternion look = Quaternion.LookRotation(direction);
transform.rotation = look;
Your target.position would be "movement". You probably also want to lerp the rotation (as you already do in your script). If you have the camera as a child of this object it wont work since childs will always rotate along with its parent (so if the character is the child it will also rotate with parent). If this is the case the best you can do is to separate them.
Thanks for the quick response @Salmjak. We just tried it and it works but we move like a side scroller left to right. Is there a similar solution or something else we can use to normalise?
If you just move like a side-scroller you can just multiply a scale-component by -1f :) Ex. transform.scale.z = transform.scale.z*1f;
This will flip the model. I'm not sure if you can edit it directly, if not, just save the scale in a temporary Vector3. Ex. Vector3 tempVec = new Vector3(transform.scale.x, transform.scale.y, transform.scale.z*-1f)