Unity操作
- 新建场景Scene
- 添加素材文件
- 创建一个Sphere,Reset重置Transform组件
- 创建一个material,给材质添加一个Shader文件,添加全景图片
- 将material添加到Sphere上,添加Audio Source组件,添加Audio Clip
- 将Camera对象移动到Sphere下,作为Sphere的子对象,Reset重置Transform组件
- 创建C# Script ,命名为RotationCamera,输入如下代码,并挂载到Camera上
代码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class RotationCamera : MonoBehaviour {
/*
需求:点击左键,实现摄像机旋转(方式一:左右 方式二:上下 方式三:八方向)
思路:通过输入方式,获取鼠标的按键 调用游戏物体的角度(自身的欧拉角)
步骤: 1判断是否点击左键
2判断旋转的方式是哪一种
3通过获取游戏物体的自身欧拉角来实现旋转!
*/
//枚举:八方向,左右,上下
public enum Rotation {MouseXAndMouseY, MouseX, MouseY }
//枚举变量
//Rotation axis;
//移动速度,灵敏度
public float speed=10f;
//绕Y轴旋转角度(X欧拉角),绕X轴旋转角度(Y欧拉角)
public float yRotation=0;
public float xRotation=0;
//限制最小最大角度值
//不能90,防止万向节死锁
public float min=-80;
public float max=80;
void Update ()
{
NewMethod(Rotation.MouseXandMouseY);
}
public void NewMethod(Rotation axis)
{
//1、判断是否点击了左键
if (Input.GetMouseButton(0))
{
//2、判断是哪一个方式
if (axis == Rotation.MouseXandMouseY)
{
//3、通过获取游戏物体(Camera)的自身欧拉角来实现旋转
//游戏物体绕x轴旋转的角度等于(欧拉角Y轴的角度)+鼠标横向移动的距离
xRotation += Input.GetAxis("Mouse X") * speed;
yRotation += Input.GetAxis("Mouse Y") * speed;
//限制Y轴旋转的角度
yRotation = Mathf.Clamp(yRotation, min, max);
//沿着X轴旋转的角度是Y的欧拉角,沿着Y轴旋转的角度是X的欧拉角的负数
transform.localEulerAngles = new Vector3(-yRotation, xRotation, 0);
print(transform.localEulerAngles);
}
//横向左右移动
if (axis == Rotation.MouseX)
{
xRotation += Input.GetAxis("Mouse X") * speed;
transform.localEulerAngles = new Vector3(0, xRotation, 0);
//transform.Rotate(0,Input.GetAxis("Mouse X")*speed,0);
}
//纵向上下移动
else if(axis == Rotation.MouseY)
{
yRotation += Input.GetAxis("Mouse Y") * speed;
yRotation = Mathf.Clamp(yRotation, min, max);
transform.localEulerAngles = new Vector3(-yRotation, 0, 0);
}
}
}
}
知识点
欧拉角Quaternion.eulerAngles
** 官方文档 **
C# => public Vector3 eulerAngles;
Description 描述
Returns the euler angle representation of the rotation.
返回表示旋转的欧拉角度。
A rotation that rotates euler.z degrees around the z axis, euler.x degrees around the x axis, and euler.y degrees around the y axis (in that order).
表示旋转的角度,绕z轴旋转euler.z度,绕x轴旋转euler.x度,绕y轴旋转euler.y度(这样的顺序)。
欧拉角(eulerAngles)旋转很好理解。
当你改变Transform组建中的 x,y,z的角度,就是改变其欧拉角。
Unity中使用的是Z-X-Y顺规。
using UnityEngine;
using System.Collections;
public class ExampleClass : MonoBehaviour {
public Quaternion rotation = Quaternion.identity;
void Example() {
rotation.eulerAngles = new Vector3(0, 30, 0);
print(rotation.eulerAngles.y);
}
}
参考
https://blog.csdn.net/bobo553443/article/details/79671174
https://blog.csdn.net/zxy13826134783/article/details/79461816
https://www.cnblogs.com/xiaohutu/p/10979936.html