English 中文(简体)
How do I make my player rotate in the current direction of my camera in Unity using C#?
原标题:

Hello I have a player with third and first person camera, I want to make my player move in the direction that my camera is looking at when I hold right mouse in third person and move(Like my player is always looking forward based on where my camera is). But my player does not rotate and I wish to implement it, I want help so that my player rotate In the current direction my camera is looking at. Also I want my player that not in the situation I mentioned above, to rotate like: W rotate forward D rotate Right, etc.. I have a method ApplyRotation but I dont think it s good enough it s kinda stiff and I dont think it fits well code:

public class PlayerMovement : MonoBehaviour
{
    [Header("Config Player")]

    [SerializeField] private float speed = 3f;
    [Tooltip("This is the Time for the player rotation - it makes smooth")][SerializeField] private float smoothTime = 0.05f;

    [SerializeField] private GameObject playerCameraObject;
    private PlayerCamera playerCamera;

    private CharacterController controller;

    private float currentSpeedRotationing;
    private float verticalVelocity = 0f;

    private Vector2 movement2D;
    private Vector3 direction;

    private bool IsGrounded() => controller.isGrounded;
    private void Awake()
    {
        controller = GetComponent<CharacterController>();
    }

    private void Start()
    {
        playerCamera = playerCameraObject.GetComponent<PlayerCamera>();
    }

    void FixedUpdate()
    {
        ApplyMovement();
        ApplyRotation();

    }


    public void OnMovement(InputAction.CallbackContext value)
    {
        movement2D = value.ReadValue<Vector2>();
        movement2D.Normalize();
        direction = new Vector3(movement2D.x, 0, movement2D.y);
        direction.Normalize();
    }

    public void OnShouldWalkBasedOnCamera(InputAction.CallbackContext value)
    {
        if (value.performed)
        {
            playerCamera.PlayerShouldRotateByCameraAngle = true;
        }
        if (value.canceled)
        {
            playerCamera.PlayerShouldRotateByCameraAngle = false;
        }

    }


    void ApplyMovement()
    {
        Vector3 currentDirection = playerCamera.CameraRotation(direction);
    }
    void ApplyRotation()
    {
        if (movement2D.sqrMagnitude == 0) return;

        float targetAngle = Mathf.Atan2(direction.x, direction.z) * Mathf.Rad2Deg;
        float angle = Mathf.SmoothDampAngle(transform.eulerAngles.y, targetAngle, ref currentSpeedRotationing, smoothTime);
        transform.rotation = Quaternion.Euler(0.0f, angle, 0.0f);

    }

using UnityEngine;
using UnityEngine.InputSystem;
public class PlayerCamera : MonoBehaviour
{
    public GameObject[] cameras;
    public bool PlayerShouldRotateByCameraAngle = false;
    [Tooltip("As It s the main camera that rotates (cinemachinebrain), it should be the main camera")]
    public Transform cameraTransform;
    private int currentIndex;

    public float lookSpeed = 2f;
    public float lookXLimit = 90;
    private float rotationX = 0;

    private void Awake()
    {
        CursorLocker(true);
    }

    private void Start()
    {
        currentIndex = 1;
    }
    public void OnChangeCamera(InputAction.CallbackContext value)
    {
        if (value.started) {

        cameras[currentIndex].SetActive(false);
        currentIndex = (currentIndex + 1) % cameras.Length;
        cameras[currentIndex].SetActive(true);
        }
    }
    private void CursorLocker(bool shouldLock)
    {
        Cursor.lockState = shouldLock ? CursorLockMode.Locked : CursorLockMode.None;
    }



public Vector3 CameraRotation(Vector3 direction)
    {
        if (PlayerShouldRotateByCameraAngle)
        {
            rotationX += -Input.GetAxis("Mouse Y") * lookSpeed;
            rotationX = Mathf.Clamp(rotationX, -lookXLimit, lookXLimit);
            cameras[currentIndex].transform.localRotation = Quaternion.Euler(rotationX, 0, 0);
            return Quaternion.AngleAxis(cameras[currentIndex].transform.rotation.eulerAngles.y, Vector3.up) * direction;
        }

        return direction;

    }

}
问题回答

暂无回答




相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

NSArray s, Primitive types and Boxing Oh My!

I m pretty new to the Objective-C world and I have a long history with .net/C# so naturally I m inclined to use my C# wits. Now here s the question: I feel really inclined to create some type of ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

How to Use Ghostscript DLL to convert PDF to PDF/A

How to user GhostScript DLL to convert PDF to PDF/A. I know I kind of have to call the exported function of gsdll32.dll whose name is gsapi_init_with_args, but how do i pass the right arguments? BTW, ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...

热门标签