- Home /
Question by
ImmanuelUchennaBest · Sep 22, 2018 at 05:03 PM ·
c#cameraplayer movementcamera rotatecamera-look
How to make the player direction change with the camera rotation?
Here is my script
using System.Collections; using UnityEngine;
public class playermovement : MonoBehaviour {
static Animator anim;
public float movementSpeed = 10.0F;
public float rotateSpeed = 100.0F;
// Use this for initialization
void Start ()
{
anim = GetComponent<Animator>();
}
// Update is called once per frame
void FixedUpdate ()
{
ControllPlayer();
if(Input.GetButtonDown("Jump"))
{
anim.SetTrigger("isThrowing");
}
if(Input.GetKeyDown("z"))
{
anim.SetTrigger("isThrowing");
}
if (Input.GetButton("Horizontal"))
{
anim.SetBool("isRunning",true);
anim.SetBool("isIdle",false);
}
else
{
anim.SetBool("isRunning",false);
anim.SetBool("isIdle",true);
}
if (Input.GetButton("Vertical"))
{
anim.SetBool("isRunning",true);
anim.SetBool("isIdle",false);
}
}
void ControllPlayer()
{
float moveHorizontal = Input.GetAxisRaw ("Horizontal");
float moveVertical = Input.GetAxisRaw ("Vertical");
Vector3 movement = new Vector3(moveHorizontal, 0.0f, moveVertical);
if (movement != Vector3.zero)
{
transform.rotation = Quaternion.Slerp (transform.rotation, Quaternion.LookRotation (movement.normalized), 0.2f);
}
transform.Translate (movement * movementSpeed * Time.deltaTime, Space.World);
}
}
Comment
Best Answer
Answer by Hellium · Sep 22, 2018 at 05:04 PM
public Transform CameraTransform ; // Drag & Drop the camera in the inspector
void ControllPlayer()
{
float moveHorizontal = Input.GetAxisRaw ("Horizontal");
float moveVertical = Input.GetAxisRaw ("Vertical");
Vector3 right = Vector3.ProjectOnPlane( CameraTransform.right, Vector3.up ) ;
Vector3 forward = Vector3.ProjectOnPlane( ( Vector3.Dot( -CameraTransform.forward, Vector3.up ) > 0.99f ) ? CameraTransform.up : CameraTransform.forward, Vector3.up ) ;
Vector3 movement = right.normalized * moveHorizontal + forward.normalized * moveVertical;
if (movement != Vector3.zero)
{
transform.rotation = Quaternion.Slerp (transform.rotation, Quaternion.LookRotation (movement.normalized), 0.2f);
}
transform.Translate (movement * movementSpeed * Time.deltaTime, Space.World);
}
Thanks for the reply. I tested the code out and it works but my player also rotate on the y axis and even moves on the y axis when the camera is facing either up or down. Do you know how to prevent that?
I've updated my answer. The object will move on the (XZ) plane only now.
Thank you so much the script works perfectly now.