Есть ли способ сделать орбиту камеры вокруг GameObject при обновлении вращения? - PullRequest
1 голос
/ 10 июля 2019

Я пытался закодировать автомобиль в Unity 5, который может двигаться как обычный автомобиль, но вокруг него вращается камера.У меня это работает, но камера не сохраняет свое положение на орбите, когда машина поворачивает.Пример: я смотрю на заднюю часть машины и поворачиваю направо.Теперь я буду смотреть на правую сторону машины.Есть ли способ заставить камеру оставаться в том же положении относительно машины?

Из этого урока я получил движение машины, но мне не понравилось движение камеры, я хотелкамера на орбиту автомобиля.Я следовал за этим для движения камеры.Однако я пытаюсь изменить его, чтобы камера поворачивалась вместе с автомобилем и не сбрасывалась на заднюю часть автомобиля.

CameraManager.cs:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class CameraManager : MonoBehaviour
{
    public InputManager im;
    public bool lockCursor;
    public float distance = 5f;
    public float mouseSensitivity = 10f;
    public Transform target;
    public Vector2 pitchMinMax = new Vector2 (-40, 85);
    public float rotationSmoothTime = 0.12f;

    Vector3 rotationSmoothVelocity;
    Vector3 currentRotation;
    float yaw;
    float pitch;

    void Start()
    {
        im = GetComponent<InputManager>();
        if (lockCursor)
        {
            Cursor.lockState = CursorLockMode.Locked;
            Cursor.visible = false;
        }
    }

    // Update is called once per frame
    void LateUpdate()
    {

        yaw += (Input.GetAxis("Mouse X")) * mouseSensitivity;
        pitch -= Input.GetAxis("Mouse Y") * mouseSensitivity;
        pitch = Mathf.Clamp(pitch, pitchMinMax.x, pitchMinMax.y);

        currentRotation = Vector3.SmoothDamp(currentRotation, new Vector3(pitch, yaw), ref rotationSmoothVelocity, rotationSmoothTime);
        transform.eulerAngles = currentRotation;

        print(target.transform.forward);
        transform.position = target.position - transform.forward * distance;

    }
}

InputManager.cs:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class InputManager : MonoBehaviour
{
    public float throttle;
    public float steer;

    // Update is called once per frame
    void Update()
    {
        throttle = Input.GetAxis("Vertical");
        steer = Input.GetAxis("Horizontal");
        print(steer);
    }
}

CarController.cs:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;


[RequireComponent(typeof(InputManager))]
[RequireComponent(typeof(Rigidbody))]
public class CarController : MonoBehaviour
{
    public InputManager im;
    public List<WheelCollider> throttleWheels;
    public List<WheelCollider> steeringWheels;
    public float strengthCo = 10000f; //Strength Coefficent
    public float maxTurn = 20f;
    public Transform CM;
    public Rigidbody rb;

    // Start is called before the first frame update
    void Start()
    {
        im = GetComponent<InputManager>();
        rb = GetComponent<Rigidbody>();

        if (CM)
        {
            rb.centerOfMass = CM.position;
        }
    }

    // Update is called once per frame
    void FixedUpdate()
    {
        foreach (WheelCollider wheel in throttleWheels)
        {
            wheel.motorTorque = strengthCo * Time.deltaTime * im.throttle;
        }
        foreach (WheelCollider wheel in steeringWheels)
        {
            wheel.steerAngle = maxTurn * im.steer;
        }
    }
}

1 Ответ

0 голосов
/ 10 июля 2019

Вы можете использовать Quaternion.Euler(currentRotation) как относительное вращение, чтобы применить к target.rotation, и применить его с target.rotation * Quaternion.Euler(currentRotation):

void LateUpdate()
{

    yaw += (Input.GetAxis("Mouse X")) * mouseSensitivity;
    pitch -= Input.GetAxis("Mouse Y") * mouseSensitivity;
    pitch = Mathf.Clamp(pitch, pitchMinMax.x, pitchMinMax.y);

    currentRotation = Vector3.SmoothDamp(currentRotation, new Vector3(pitch, yaw), ref rotationSmoothVelocity, rotationSmoothTime);
    transform.rotation = target.rotation * Quaternion.Euler(currentRotation);

    print(target.transform.forward);
    transform.position = target.position - transform.forward * distance;

}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...