1.移动场景中的物体
using UnityEngine;
using System.Collections;
public class DragAndDrog : MonoBehaviour {
private GameObject target;
private bool isMouseDrag;
private Vector3 screenPosition;
private Vector3 offset;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
GameObjectDragAndDrog();
}
//任意拖拽
private GameObject ReturnGameObjectDrag(out RaycastHit hit)
{
target = null;
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray.origin, ray.direction * 10, out hit))
{
target = hit.collider.gameObject;
}
return target;
}
//拖拽Updata
private void GameObjectDragAndDrog()
{
if (Input.GetMouseButtonDown (0))
{
RaycastHit hitInfo;
target = ReturnGameObjectDrag(out hitInfo);
if (target != null)
{
isMouseDrag = true;
//将目标对象的世界坐标转化为屏幕坐标
screenPosition = Camera.main.WorldToScreenPoint(target.transform.position);
//得到鼠标的世界坐标与目标世界坐标的偏移量
offset = target.transform.position - Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPosition.z));
}
}
if (Input.GetMouseButtonUp(0))
{
isMouseDrag = false;
}
if (isMouseDrag)
{
Vector3 currentScreenSpace = new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPosition.z);
//鼠标的世界坐标加上偏移量,即为目标对象的终点
Vector3 currentPosition = Camera.main.ScreenToWorldPoint(currentScreenSpace) + offset;
//
target.transform.localPosition = new Vector3(currentPosition.x, currentPosition.y, currentPosition.z);
}
}
}
本脚本可以加载任意一个对象GameObject,场景中所有带Collider的对象,当鼠标点击拖动时候都可以沿x和z轴拖动。之前,都是要拖动那个GameObject就会写一个脚本挂在上面,今天实现了不用每一个要拖动的GameObject都挂载脚本,也不用将移动的GameObject赋给某个变量。
2。鼠标滚轮控制视野
void Update () {
//鼠标滚轮的效果
//Camera.main.fieldOfView 摄像机的视野
//Camera.main.orthographicSize 摄像机的正交投影
//Zoom out
if (Input.GetAxis("Mouse ScrollWheel") < 0)
{
if (Camera.main.fieldOfView <= 100)
Camera.main.fieldOfView += 2;
if (Camera.main.orthographicSize <= 20)
Camera.main.orthographicSize += 0.5F;
}
//Zoom in
if (Input.GetAxis("Mouse ScrollWheel") > 0)
{
if (Camera.main.fieldOfView > 2)
Camera.main.fieldOfView -= 2;
if (Camera.main.orthographicSize >= 1)
Camera.main.orthographicSize -= 0.5F;
}
}