在场景中新建一个cube,创建两个代码,分别为move,scroller;move挂在cube上,scroller挂在摄像机上。
1,鼠标滑轮实现场景缩放:
void Update () {
//获取坐标轴中滑轮的信息,如果滑轮上滑,则为正,下为负
if(Input.GetAxis("Mouse ScrollWheel")<0)
{
//相机的视野夹角
if (Camera.main.fieldOfView <= 100)
{
Camera.main.fieldOfView += 2;
}
}
if(Input.GetAxis("Mouse ScrollWheel") > 0)
{
if (Camera.main.fieldOfView > 6)
{
Camera.main.fieldOfView -= 2;
}
}
}
2.鼠标拖动物体实现cube的移动
先求出场景中物体世界坐标和鼠标点击的屏幕坐标的差值,然后把鼠标点击的位置的坐标转化成世界坐标,再将物体的坐标转化成屏幕坐标
void Start () {
StartCoroutine(OnMouseDown());
}
// Update is called once per frame
void Update () {
}
IEnumerator OnMouseDown()
{
//将物体由世界坐标系转换成屏幕坐标系
Vector3 screenPos = Camera.main.WorldToScreenPoint(transform.position);
//计算出物体和鼠标坐标的差值
Vector3 offset = transform.position - Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y
, screenPos.z));
while (Input.GetMouseButton(0))
{
//当鼠标点击时,就把物体的坐标变成鼠标点击的坐标
Vector3 mousePos = new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPos.z);
Vector3 curPos = offset + Camera.main.ScreenToWorldPoint(mousePos);
transform.position = curPos;
yield return new WaitForFixedUpdate();
Debug.Log(121);
}
}