我正在研究RTS摄像机的运动, 我正在努力控制它的运动 根据地图大小和相机的四角。
这是我的代码:
public void Init(Vector2 mapSize)
{
_camera = GetComponent<Camera>();
_movePosition = transform.position =
new Vector3(CameraStartPosition.x, CameraHeight, CameraStartPosition.z);
var frustumHeight = 2.0f * CameraHeight * Mathf.Tan(_camera.fieldOfView * 0.5f * Mathf.Deg2Rad);
var frustumWidth = frustumHeight * _camera.aspect;
var floorZSize = mapSize.y * _mapScaleFactor;
var angle = Mathf.Sin(transform.localRotation.eulerAngles.x * Mathf.Deg2Rad);
var distance = frustumHeight * 0.5f / Mathf.Tan(_camera.fieldOfView * 0.5f * Mathf.Deg2Rad);
var hypotenuse = distance / angle;
var adjacent = Mathf.Sqrt(Mathf.Pow(hypotenuse,2) - Mathf.Pow(distance,2));
var zMax = floorZSize - adjacent ;
var zMin = floorZSize + adjacent ;
Debug.Log(
$"frustumWidth: {frustumWidth} frustumHeight: {frustumHeight} " +
$"filed of view: {_camera.fieldOfView} distance: {distance} " +
$"mapHeight {floorZSize} angle{angle} hypotenuse: {hypotenuse} adjacent: {adjacent} zMax: {zMax} zMin: {zMin}");
BoundsMin = new Vector3(
_mapScaleFactor*(-mapSize.x) + CameraHeight*Mathf.Sin(transform.localRotation.eulerAngles.z*Mathf.Deg2Rad),
CameraHeight,
-zMin);
BoundsMax = new Vector3(
_mapScaleFactor*mapSize.x + CameraHeight*Mathf.Sin(transform.localRotation.eulerAngles.z*Mathf.Deg2Rad),
CameraHeight,
zMax );
}
private void Update()
{
if (_camera == null) return;
if (Input.GetKey(_moveUp.Key))
{
_movePosition.z += MovementSpeed * Time.deltaTime;
}
if (Input.GetKey(_moveRight.Key))
{
_movePosition.x += MovementSpeed * Time.deltaTime;
}
if (Input.GetKey(_moveDown.Key))
{
_movePosition.z -= MovementSpeed * Time.deltaTime;
}
if (Input.GetKey(_movLeft.Key))
{
_movePosition.x -= MovementSpeed * Time.deltaTime;
}
var cameraMoveDirection = (_movePosition - transform.position).normalized;
var distance = Vector3.Distance(_movePosition,transform.position);
_movePosition = new Vector3(
Mathf.Clamp(_movePosition.x, BoundsMin.x, BoundsMax.x),
Mathf.Clamp(_movePosition.y, BoundsMin.y, BoundsMax.y),
Mathf.Clamp(_movePosition.z, BoundsMin.z, BoundsMax.z));
if (distance > 0)
{
var newCameraPosition = transform.position + (cameraMoveDirection * distance * MovementSpeed * Time.deltaTime);
newCameraPosition = new Vector3(
Mathf.Clamp(newCameraPosition.x, BoundsMin.x, BoundsMax.x),
Mathf.Clamp(newCameraPosition.y, BoundsMin.y, BoundsMax.y),
Mathf.Clamp(newCameraPosition.z, BoundsMin.z, BoundsMax.z));
var distanceAfterMoving = Vector3.Distance(newCameraPosition, _movePosition);
if (distanceAfterMoving > distance)
{
newCameraPosition = _movePosition;
}
transform.position = newCameraPosition;
}
}
所以我知道如何获得所有值,例如相机三角形的角度,距离,斜边和相邻,但是我知道相机的三角函数中仍然缺少某些内容。
我当前相机的X轴旋转角度是40。
为了让自己更清楚,我希望当摄影机位置为MapXMin-cameraLeftCorner时,摄影机运动会受到限制。
有人可以帮我弄清楚我在做什么错吗?