Hola, soy muy nuevo en Unity y solo tengo conocimientos básicos. Creé un jugador que puede moverse y también una cámara que sigue al jugador y de acuerdo con el mouseX y mouseY acis, la cámara gira. Ahora quiero que el ángulo de rotación de la cámara sea la posición delantera.
Si el jugador presiona w, se mueve a lo largo de x acis pero si el ángulo de la cámara cambia y el jugador presiona w, debería moverse en esta dirección. jugador.cs
using System.Collections; using System.Collections.Generic; using UnityEngine; public class DoublePlayer : MonoBehaviour { private CharacterController _controller; public float _jumpHeight = 3f; [SerializeField] private float _moveSpeed = 5f; [SerializeField] private float _gravity = 9.81f; private float _directionY; void Start() { _controller = GetComponent<CharacterController>(); } // Update is called once per frame void Update() { float horizontalInput = Input.GetAxis("Horizontal"); float verticalInput = Input.GetAxis("Vertical"); Vector3 direction = new Vector3(horizontalInput, 0, verticalInput); // set gravity _directionY -= _gravity * Time.deltaTime; direction.y = _directionY; _controller.Move(direction * _moveSpeed * Time.deltaTime); } }cámara.cs
public class CameraController : MonoBehaviour { public float RotationSpeed = 1; public Transform Target, Player; float mouseX, mouseY; void Start() { Cursor.visible = false; Cursor.lockState = CursorLockMode.Locked; } // Update is called once per frame void LateUpdate() { CamControl(); } void CamControl() { mouseX += Input.GetAxis("Mouse X") * RotationSpeed; mouseY += Input.GetAxis("Mouse Y") * RotationSpeed; mouseY = Mathf.Clamp(mouseY, -35, 60); transform.LookAt(Target); Target.rotation = Quaternion.Euler(mouseY, mouseX, 0); Player.rotation = Quaternion.Euler(0, mouseX, 0); } }Para la variable Target y Player, seleccioné el objeto del jugador. ¿Alguien tiene una solución simple que pueda entender?
Simplemente puede tomar la direction y rotarla junto con el objeto al que está conectado el componente usando el operador Quaternion * Vector3
var rotatedDirection = transform.rotation * direction;O si prefiere la orientación de la otra secuencia de comandos adjunta a un objeto diferente, hágalo, por ejemplo.
// link your camera or whatever shall be used for the orientation via the Inspector [SerializeField] private Transform directionProvider;y luego
var rotatedDirection = directionProvider.rotation * direction;Como está obteniendo la rotación directamente de Transform , podría usar Transform.TransformDirection :
Vector3 rotatedDirection = transform.TransformDirection(direction);