DotCloud/Assets/TestCameraMover.cs

101 lines
3.3 KiB
C#

using System;
using System.Collections;
using System.Collections.Generic;
using Unity.Mathematics;
using UnityEngine;
namespace ZC
{
public class TestCameraMover : MonoBehaviour
{
[SerializeField] private Camera _camera;
[SerializeField] private float _moveSpeed = 1;
[SerializeField] private float _rotateSpeed = 1;
[SerializeField] private Rect _regions;
private float _destination;
private bool _startRotating;
[SerializeField]
private float _t;
// Start is called before the first frame update
void Start()
{
this._camera.transform.position = new Vector3(0.945037186f, 9.69658566f, -23.7757969f);
this._camera.transform.rotation = Quaternion.Euler(55, 0, 0);
}
// Update is called once per frame
void Update()
{
Vector3 vector3 = Vector3.ProjectOnPlane(this._camera.transform.forward, Vector3.up);
this._camera.transform.position += vector3 * (this._moveSpeed * Time.deltaTime);
if (!_regions.Contains(this._camera.transform.position))
{
vector3 *= -1;
this._camera.transform.position += vector3 * (2 * this._moveSpeed * Time.deltaTime);
RotateTo(vector3);
}
else
{
if (!_startRotating && UnityEngine.Random.value > 0.8f)
{
_startRotating = true;
_destination = this._camera.transform.rotation.eulerAngles.y + UnityEngine.Random.Range(-180f, 180);
_destination = WrapAngle(_destination);
}
}
if (_startRotating)
{
var currentY = this._camera.transform.rotation.eulerAngles.y;
if (Mathf.DeltaAngle(currentY, this._destination) < 0.5f)
{
_startRotating = false;
}
else
{
currentY = WrapAngle(currentY);
int sign = Math.Sign(this._destination - currentY);
var rotateSpeed = ( sign* this._rotateSpeed * Time.deltaTime) / (this._destination - currentY);
this._t = rotateSpeed;
var angle = Mathf.LerpAngle(currentY, this._destination, rotateSpeed);
var rotationEulerAngles = this._camera.transform.rotation.eulerAngles;
this._camera.transform.rotation = Quaternion.Euler(rotationEulerAngles.x, angle, 0);
}
}
}
static float WrapAngle(float angle)
{
while (true)
{
if (angle < 0)
{
angle += 360;
}
else if (angle > 360)
{
angle -= 360;
}
else
return angle;
}
}
void RotateTo(Vector3 dir)
{
Quaternion quaternion = Quaternion.LookRotation(dir.normalized);
float y = quaternion.eulerAngles.y;
var rotationEulerAngles = this._camera.transform.rotation.eulerAngles;
this._camera.transform.rotation = Quaternion.Euler(rotationEulerAngles.x, y, 0);
}
}
}