I have a script where I can strafe left and right with arrow keys, and move forward and back as well.
I’m trying to get the forward to be relative to rotation set to mouse position x.
I have this: below;
but am looking for a more simple way as the turn doesn’t react as quickly as I need an on release of button it snaps back.
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class PlayerMovement : MonoBehaviour {
Animator anim;
Rigidbody rb;
Vector3 hitr;
Vector3 hitrn;
Vector3 player;
Quaternion TargetRotation;
float speed = 150f;
public float turnInput = 50f;
public float rotateVel = 50f;
public Quaternion targetRotation
{
get { return TargetRotation; }
}
void Start()
{
TargetRotation = transform.rotation;
rb = GetComponent<Rigidbody> ();
anim = GetComponent<Animator> ();
}
void Update ()
{
Move ();
Turning ();
}
void FixedUpdate()
{
//inclines
RaycastHit hit;
Physics.Raycast (transform.position, Vector3.down, out hit);
if(Physics.Raycast(transform.position, Vector3.down, .5f))
{
transform.up = hit.normal;
hitrn = hitr - transform.eulerAngles;
transform.Rotate(hitrn.x, 0, hitrn.z);
}
}
void Move()
{
float forward = Input.GetAxis ("Vertical");
anim.SetFloat ("Speed", forward);
float sideways = Input.GetAxis ("Horizontal");
anim.SetFloat ("Direction", sideways);
Vector3 movement = new Vector3 (sideways, 0f, forward);
rb.AddForce (movement * speed);
}
void Turning()
{
float turn = Input.GetAxis ("Mouse X");
if (Input.GetKey(KeyCode.Mouse0))
{
TargetRotation *= Quaternion.AngleAxis (rotateVel * turn * Time.deltaTime, Vector3.up);
transform.rotation = TargetRotation;
}
}
}