- Home /
Make the player go into the direction I am looking at
Hi, I am having trouble with my animated FPS character.
I made this script and attached it to the camera. And yes the player rotates with the camera but when I move I am still moving towards the standard directions and the animation is playing towards the standard direction. Sorry for my bad English btw.
Vector2 mouseLook;
Vector2 smoothV;
public float sensitivity = 5.0f;
public float smoothing = 2.0f;
GameObject character;
// Use this for initialization
void Start ()
{
character = this.transform.parent.gameObject;
}
// Update is called once per frame
void Update ()
{
var md = new Vector2(Input.GetAxisRaw("Mouse X"), Input.GetAxisRaw("Mouse Y"));
md = Vector2.Scale(md, new Vector2(sensitivity * smoothing, sensitivity * smoothing));
smoothV.x = Mathf.Lerp(smoothV.x, md.x, 1f / smoothing);
smoothV.y = Mathf.Lerp(smoothV.y, md.y, 1f / smoothing);
mouseLook += smoothV;
transform.localRotation = Quaternion.AngleAxis(-mouseLook.y, Vector3.right);
character.transform.localRotation = Quaternion.AngleAxis(mouseLook.x, character.transform.up);
}
This is my player script:
public Animator anim;
public Rigidbody Rbody;
public float Gravity;
public float JumpHeight;
private float currentrunspeed = 80;
private bool run;
//public GameObject Camera;
public GameObject us;
private float inputH;
private float inputV;
private float inputJump;
// Use this for initialization
void Start ()
{
anim = GetComponent<Animator>();
Rbody = GetComponent<Rigidbody>();
run = false;
Cursor.lockState = CursorLockMode.Locked;
}
// Update is called once per frame
void Update ()
{
transform.localEulerAngles = new Vector3(transform.localEulerAngles.x, Camera.main.transform.localEulerAngles.y, transform.localEulerAngles.z);
Physics.gravity = new Vector3(0f, -Gravity * Time.fixedDeltaTime, 0f);
if (Input.GetKeyDown("1"))
{
anim.Play("Run", -1,0f);
}
if (Input.GetKey(KeyCode.LeftShift)&& inputV > 0.1)
{
currentrunspeed = 150f;
run = true;
}
else
{
run = false;
currentrunspeed = 80f;
}
inputH = Input.GetAxis("Horizontal");
inputV = Input.GetAxis("Vertical");
anim.SetFloat("InputH", inputH);
anim.SetFloat("InputV", inputV);
anim.SetBool("Run",run);
float moveX = inputH * 50f * Time.deltaTime;
float moveZ = inputV * currentrunspeed * Time.deltaTime;
Rbody.velocity = new Vector3(moveX,Rbody.velocity.y, moveZ);
if (Input.GetKeyDown("space") && IsGrounded)
{
Rbody.AddForce(Vector3.up * JumpHeight * Time.deltaTime);
anim.SetBool("Jump", true);
}
else
{
anim.SetBool("Jump", false);
}
}
public bool IsGrounded;
void OnCollisionStay(Collision collisionInfo)
{
IsGrounded = true;
}
void OnCollisionExit(Collision collisionInfo)
{
IsGrounded = false;
}
If someone knows any solutions I'd really appreciate it XD.
Comment