【发布时间】:2019-07-10 01:11:02
【问题描述】:
我一直在尝试在 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;
}
}
}
【问题讨论】:
-
无需在代码中执行此操作。制作一个作为汽车子对象的游戏对象,并将其放置在您希望发生旋转的位置。将相机对准该游戏对象指向汽车,然后将其移到您想要的任意位置。旋转游戏对象。当汽车绕汽车运行时,摄像头将继续指向汽车。