I’m working on a top down 3rd person game
player object has playermovement script attached
using UnityEngine;
using System.Collections;
public class PlayerMovement : MonoBehaviour
{
CharacterController _controller;
[SerializeField]
float _moveSpeed = 5.0f;
[SerializeField]
float _walkSpeed = 2.0f;
[SerializeField]
float _runSpeed = 10.0f;
[SerializeField]
float _gravity = 1.0f;
float _yVelocity = 0.0f;
bool _walking = false;
public Quaternion _lookrotation;
void Start ()
{
_controller = GetComponent<CharacterController>();
}
void FixedUpdate ()
{
float h = Input.GetAxis ("Horizontal");
float v = Input.GetAxis ("Vertical");
MouseLook();
Move (h,v);
}
void Move(float h, float v)
{
Vector3 direction = new Vector3(h, 0, v);
Vector3 velocity = direction * _moveSpeed;
if (Input.GetKeyDown ("left ctrl"))
{
_walking = !_walking;
}
if (_walking == true)
{
velocity = direction * _walkSpeed;
}
if (Input.GetKey ("left shift"))
{
velocity = direction * _runSpeed;
}
_yVelocity -= _gravity;
velocity.y = _yVelocity;
//velocity = transform.TransformDirection (velocity); commented out due rotation probs with mouselook
_controller.Move (velocity * Time.deltaTime);
}
void MouseLook()
{
Ray camRay = Camera.main.ScreenPointToRay (Input.mousePosition);
RaycastHit mouseloc;
if(Physics.Raycast(camRay,out mouseloc, 100))
{
Vector3 playertomouse = mouseloc.point - transform.position;
playertomouse.y = 0f;
_lookrotation = Quaternion.LookRotation(playertomouse);
transform.rotation = _lookrotation;
}
}
}
The main camera is a child object to an empty game object called CamFocus, CamFocus has the CamMovement script attached to it
using UnityEngine;
using System.Collections;
public class CamMovement : MonoBehaviour
{
public Transform _targetpos;
public float _camsmoothing = 5f;
float _camrotation;
Vector3 _currentrot;
void Start ()
{
transform.position = _targetpos.transform.position;
}
void FixedUpdate ()
{
Vector3 targetcampos = _targetpos.position;
transform.position = Vector3.Lerp (transform.position, targetcampos, _camsmoothing * Time.deltaTime);
_camrotation = Input.GetAxis("Rotation");
_currentrot = transform.localEulerAngles;
_currentrot.y += _camrotation * _camsmoothing;
transform.localEulerAngles = _currentrot;
}
}
the end result of this is that the players rotation is always set to look at the mouse location on screen, he moves with a standard wasd movement scheme maintaining his rotation to look at the mouse location
the problem I am having is when I added the Camera rotation ability the camera rotation works, but the players movement orientation stays the same, I took a break from this for a while and have just come back to it. I believe the answer lies in Quaternions but I’ve always kinda sucked at them… could somebody point me in the right direction?
I need movement orientation to always remain in line with the camera, but the player rotation has to continue to focus on mouse point on screen.