Tengo un guión simple para moverme y mirar alrededor cuando giro, la cámara no gira con el personaje, ¿cómo hago para que giren juntos?
using System.Collections.Generic; using UnityEngine; public class PlayerFollow : MonoBehaviour { public Transform PlayerTransform; private Vector3 _cameraOffset; public float rotationSpeed = 1; public Transform Target, Player; float mouseX, mouseY; [Range(0.01f, 1.0f)] public float SmoothFactor = 0.5f; public bool LookAtPlayer = false; // Start is called before the first frame update void Start() { _cameraOffset = transform.position - PlayerTransform.position; Cursor.visible = false; Cursor.lockState = CursorLockMode.Locked; } // Update is called once per frame void LateUpdate() { CamControl(); Vector3 newPos = PlayerTransform.position + _cameraOffset; transform.position = Vector3.Slerp(transform.position, newPos, SmoothFactor); /*if(LookAtPlayer){ transform.LookAt(PlayerTransform); }*/ } void CamControl() { mouseX += Input.GetAxis("Mouse X") * rotationSpeed; mouseY += Input.GetAxis("Mouse Y") * rotationSpeed * -1; mouseY = Mathf.Clamp(mouseY, -35, 60); transform.LookAt(Target); Target.rotation = Quaternion.Euler(mouseY, mouseX, 0); Player.rotation = Quaternion.Euler(0, mouseX, 0); } }
Creo que deberías hacer que la cámara sea hija del jugador y luego adjuntar este código al jugador.
using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlayerMovement : MonoBehaviour { public CharacterController characterController; public float speed; private Vector3 camRotation; private Transform cam; private Vector3 moveDirection; [Range(-45, -15)] public int minAngle = -30; [Range(30, 80)] public int maxAngle = 45; [Range(50, 500)] public int sensitivity = 200; private void Awake() { cam = Camera.main.transform; } void Update() { Move(); Rotate(); } private void Rotate() { transform.Rotate(Vector3.up * sensitivity * Time.deltaTime * Input.GetAxis("Mouse X")); camRotation.x -= Input.GetAxis("Mouse Y") * sensitivity * Time.deltaTime; camRotation.x = Mathf.Clamp(camRotation.x, minAngle, maxAngle); cam.localEulerAngles = camRotation; } private void Move() { float horizontalMove = Input.GetAxis("Horizontal"); float verticalMove = Input.GetAxis("Vertical"); if (characterController.isGrounded) { moveDirection = new Vector3(horizontalMove, 0, verticalMove); moveDirection = transform.TransformDirection(moveDirection); } moveDirection.y -= gravity * Time.deltaTime; characterController.Move(moveDirection * speed * Time.deltaTime); } }
No olvide agregar un controlador de personaje al reproductor y luego asignarlo en el inspector.