I’m using a camera to drive player movement as per the code below, but rather than travelling in a straight line forward the player actually travels in towards 2 o’clock (assuming 12 noon is forward) - and I have no idea why.
As is probably obvious, I’m new to this stuff…please could you kindly explain any answers using small words. Thanks
public class CameraController : MonoBehaviour
{
public Transform target;
public Vector3 offset;
public bool useOffsetValues;
public float rotateSpeed;
public Transform pivot;
//public float speed;
// Start is called before the first frame update
void Start()
{
if (!useOffsetValues){
offset = target.position - transform.position;
}
pivot.transform.position = target.transform.position;
pivot.transform.parent = target.transform;
//hide mouse pointer
Cursor.lockState = CursorLockMode.Locked;
}
// Update is called once per frame
void LateUpdate()
{
// get the x position of the mouse and rotate the target
float horizontal = Input.GetAxisRaw("Mouse X")*rotateSpeed;
target.Rotate(0,horizontal,0);
//Get the Y position of the mouse & rotate pivot for camera
float vertical = Input.GetAxisRaw("Mouse Y")*rotateSpeed;
pivot.Rotate(-vertical,0,0);
// move the camera based on the current rotation of the target and the original offset
float desiredYAngle = target.eulerAngles.y;
float desiredXAngle = pivot.eulerAngles.x;
Quaternion rotation = Quaternion.Euler(desiredXAngle,desiredYAngle,0);
transform.position = target.position-rotation*offset;
if(transform.position.y < target.position.y){
transform.position = new Vector3(transform.position.x, target.position.y-.5f, transform.position.z);
}
transform.LookAt(target);
//transform.position = target.position - offset;
}
}
public class PlayerController : MonoBehaviour
{
public float moveSpeed;
public float jumpForce = 5f;
public CharacterController controller;
Vector3 moveDirection;
public float gravityScale;
// Start is called before the first frame update
void Start()
{
controller = GetComponent<CharacterController>();
}
// Update is called once per frame
void Update()
{
float yStore = moveDirection.y;
moveDirection = (transform.forward*Input.GetAxisRaw("Vertical")+transform.right*Input.GetAxisRaw("Horizontal"));
moveDirection = moveDirection.normalized*moveSpeed;
moveDirection.y = yStore;
if(controller.isGrounded)
{
moveDirection.y = 0f;
if(Input.GetButtonDown("Jump"))
{
moveDirection.y = jumpForce;
}
}
moveDirection.y = moveDirection.y + Physics.gravity.y*gravityScale*Time.deltaTime;
controller.Move(moveDirection*Time.deltaTime);
}
}