2012-12-10 23:05:00 chinalofthjh 阅读数 298
/*
Touch Orbit
Programmed by: Randal J. Phillips (Caliber Mengsk)
Original Creation Date: 12/16/2011
Last Updated: 12/16/2011
Desctiption: Simple orbit by one touch and drag, as well as pinch to zoom with two fingers.
*/


var x:float;

var y:float;

var xSpeed:float;

var ySpeed:float;

var pinchSpeed:float;

var distance:float = 10;

var minimumDistance:float = 5;

var maximumDistance:float = 100;

private var touch:Touch;

private var lastDist:float = 0;

private var curDist:float = 0;

private var gameCamera:Camera;

function Start ()

{

gameCamera = Camera.mainCamera;

}


function Update ()

{

if (Input.GetKeyDown(KeyCode.Escape))

{

Application.Quit();

}


if (Input.touchCount == 1 && Input.GetTouch(0).phase == TouchPhase.Moved)

{

//One finger touch does orbit

touch = Input.GetTouch(0);

x += touch.deltaPosition.x * xSpeed * 0.02;

y -= touch.deltaPosition.y * ySpeed * 0.02;

}

if (Input.touchCount > 1 && (Input.GetTouch(0).phase == TouchPhase.Moved || Input.GetTouch(1).phase == TouchPhase.Moved))

{

//Two finger touch does pinch to zoom

var touch1 = Input.GetTouch(0);

var touch2 = Input.GetTouch(1);

curDist = Vector2.Distance(touch1.position, touch2.position);

if(curDist > lastDist)

{

distance += Vector2.Distance(touch1.deltaPosition, touch2.deltaPosition)*pinchSpeed/10;

}else{

distance -= Vector2.Distance(touch1.deltaPosition, touch2.deltaPosition)*pinchSpeed/10;

}



lastDist = curDist;

}


if(distance <= minimumDistance)

{

//minimum camera distance

distance = minimumDistance;

}



if(distance >= maximumDistance)

{

//maximum camera distance

distance = maximumDistance;

}



//Sets rotation

var rotation = Quaternion.Euler(y, x, 0);



//Sets zoom

var position = rotation * Vector3(0.0, 0.0, -distance) + Vector3(0,0,0);



//Applies rotation and position

transform.rotation = rotation;

transform.position = position;

}



function OnGUI()

{

//Simple output to display the distance from the center

GUI.Label(Rect(0,0,Screen.width, Screen.height),distance.ToString());

}
2019-05-15 16:13:10 q764424567 阅读数 2045

一、前言

以前转载了一篇关于在Unity3d中鼠标控制物体的旋转、移动、缩放的代码
然后发现错误比较多,就重新写了一个代码,自我感觉简单实用。。。特意分享出来供大家参考
原文章也贴出来吧
【Unity3d 鼠标滚动拉近模型、鼠标右键旋转模型、鼠标中键拖拽模型】
https://blog.csdn.net/q764424567/article/details/78630649

效果图:
在这里插入图片描述

二、知识点

  • Input.GetMouseButton(0)
    获取鼠标输入,参数为一个int值
    为0的时候获取的是左键

  • Input.GetMouseButton(1)
    为1的时候获取的是右键

  • Input.GetMouseButton(2)
    为2的时候获取的是中键(就是那个滑轮)

  • Input.GetMouseButton
    鼠标按压

  • Input.GetMouseButtonUp
    鼠标点击

  • Input.GetMouseButtonDown
    鼠标松开

  • Camera.main.ScreenToWorldPoint
    屏幕坐标转化为世界坐标

  • Quaternion rotation = Quaternion.Euler(0, 0, 0);
    欧拉角转化为四元数

三、代码分享

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class MouseControlModel : MonoBehaviour
{
    //旋转最大角度
    public int yMinLimit = -20;
    public int yMaxLimit = 80;
    //旋转速度
    public float xSpeed = 250.0f;
    public float ySpeed = 120.0f;
    //旋转角度
    private float x = 0.0f;
    private float y = 0.0f;

    void Update()
    {
        if (Input.GetMouseButton(0))
        {
            //将屏幕坐标转化为世界坐标  ScreenToWorldPoint函数的z轴不能为0,不然返回摄像机的位置,而Input.mousePosition的z轴为0
            //z轴设成10的原因是摄像机坐标是(0,0,-10),而物体的坐标是(0,0,0),所以加上10,正好是转化后物体跟摄像机的距离
            Vector3 temp = Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, 10));
            transform.position = temp;
        }
        else if (Input.GetMouseButton(1))
        {
            //Input.GetAxis("MouseX")获取鼠标移动的X轴的距离
            x += Input.GetAxis("Mouse X") * xSpeed * 0.02f;
            y -= Input.GetAxis("Mouse Y") * ySpeed * 0.02f;
            y = ClampAngle(y, yMinLimit, yMaxLimit);
            //欧拉角转化为四元数
            Quaternion rotation = Quaternion.Euler(y, x, 0);
            transform.rotation = rotation;
        }
        else if (Input.GetAxis("Mouse ScrollWheel") != 0)
        {
            //鼠标滚动滑轮 值就会变化
            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;
            }
        }
    }

    //角度范围值限定
    static float ClampAngle(float angle, float min, float max)
    {
        if (angle < -360)
            angle += 360;
        if (angle > 360)
            angle -= 360;
        return Mathf.Clamp(angle, min, max);
    }
}

谢谢大家!

2013-07-26 17:30:43 wyz365889 阅读数 6694

基本功能实现:物体通过鼠标左键上下移动,中间键缩放、右键旋转,30秒没操作,物体自动旋转


实例代码:

using UnityEngine;
using System.Collections;


public class Script_07_11 : MonoBehaviour 
{

	public Transform target;
	
	private int MouseWheelSensitivity = 50;
	private int MouseZoomMin = 20;
	private int MouseZoomMax = 112;
	private float normalDistance = 500;
	
	private bool flag_Roable = true;	//自动旋转标志
	
	private Vector3 normalized;
	

	private float xSpeed = 250.0f;
	private float ySpeed = 120.0f;


	private float x = 0.0f;
	private float y = 0.0f;
	

	private System.DateTime  oldTime;
	private System.DateTime  nowTime;

	void Start () 
	{
		
		oldTime = System.DateTime.Now;
		//transform.LookAt(target);
		
		
	}
	
	void Update ()
	{
		nowTime = System.DateTime .Now;
		System.TimeSpan	 ts1 = new System.TimeSpan(oldTime.Ticks);
		System.TimeSpan	 ts2 = new System.TimeSpan(nowTime.Ticks);
		
		System.TimeSpan ts =  ts2.Subtract(ts1).Duration();
		
		if(ts.Seconds>30 && !Input.anyKey)
		{
			flag_Roable = true;
			oldTime = System.DateTime.Now;
		}
		
		if(flag_Roable && Input.anyKey)
		{
			flag_Roable = false;
		}
		
		if(flag_Roable)	//自动旋转
		{
			
			x-=Time.deltaTime*30;
			
			
			var rotation = Quaternion.Euler(0,x,0);
			transform.RotateAround(target.position,Vector3.up,0.3f);	
		}
		else
		{
			if(Input.GetMouseButton(1))
			{
				if(Input.GetAxis("Mouse X")<0)   
					transform.RotateAround(target.position,Vector3.down,4); 
				if(Input.GetAxis("Mouse X")>0)
					transform.RotateAround(target.position,Vector3.up,4);
			}
			else if (Input.GetAxis("Mouse ScrollWheel") != 0)
			{
				
			    //normalized = (transform.position - CameraTarget).normalized;
				
				if (normalDistance >= MouseZoomMin && normalDistance <= MouseZoomMax)
				{
					normalDistance -= Input.GetAxis("Mouse ScrollWheel") * MouseWheelSensitivity;
				}
				if (normalDistance < MouseZoomMin)
				{
					normalDistance = MouseZoomMin;
				}
				if (normalDistance > MouseZoomMax)
				{
					normalDistance = MouseZoomMax;
				}
					//transform.position =	   normalized * normalDistance;
				transform.camera.fieldOfView = normalDistance;
				
			}
			else if(Input.GetMouseButton(0))
			{
				//print("wyz-==="+Input.GetAxis("Mouse Y"));
				if(Input.GetAxis("Mouse Y")<0)  //down
				{
					Vector3 temp=Vector3.up * 60.0f * Time.deltaTime;
					
					print("wyz==up==="+transform.localPosition.y);
					if(transform.localPosition.y>300)
					{
						temp=Vector3.up * 5.0f * Time.deltaTime;
						transform.Translate(temp);
					}
					else
					{
						transform.Translate(temp);		
					}
				}
						
				if(Input.GetAxis("Mouse Y")>0)  //up 
				{
					print("wyz==donw==="+transform.localPosition.y);
					Vector3 temp=Vector3.down * 60.0f * Time.deltaTime;
				
					
					if(transform.localPosition.y<-300)
					{
						temp=Vector3.up * 5.0f * Time.deltaTime;
						transform.Translate(temp);
					}
					else
					{
						transform.Translate(temp);				
					}			
				}
			
			}	
			
		}
		
	}
	
	
}


2019-03-21 15:00:39 zjh_368 阅读数 358

此脚本挂在 Camera(摄像机)上。

定位模型用作查找模型后定位到该模型的跟前,然后拥有下面的操作功能;

类似编辑器模式下的操作,用作浏览模型使用,旋转、拖动和缩放均是操作的Camera(摄像机)位移;

高亮使用了HighlightingSystem插件;

中心点并非模型的transform.position,而是模型的正中心,因为有些模型的position不是模型正中心,所以需要此方法。

using HighlightingSystem;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class Test01 : MonoBehaviour {

    public Transform obj;
    float maxX, maxY, maxNum;
    //float minx, minY, minZ;
    private Vector3 centerPoint;

    #region 浏览模型操控属性
    /// <summary>
    /// 缩放距离
    /// </summary>
    public float ZoomSpeed = 30;
    /// <summary>
    /// 拖动速度
    /// </summary>
	public float MovingSpeed = 0.5f;
    /// <summary>
    /// 视角摆动速度
    /// </summary>
	public float RotateSpeed = 1;
    /// <summary>
    /// 摄像机旋转速度
    /// </summary>
    public float distance = 30;

    Quaternion rotation;
    Vector3 position;
    float delta_x, delta_y, delta_z;
    float delta_rotation_x, delta_rotation_y; 
    #endregion

   

    void Start () {
        //计算模型正前方位置点
        Mesh mesh = obj.GetComponent<MeshFilter>().mesh;
        Vector3[] vertices = mesh.vertices;
        //minZ = obj.position.z;
        //计算得到最值顶点,判断模型的最长或最宽,用来计算定位点的离模型的距离
        foreach (Vector3 item in vertices)
        {
            if (item.x > maxX)
            {
                maxX = item.x;
            }
            if (item.y > maxY)
            {
                maxY = item.y;
            }
        }

        centerPoint = GetCenter(obj.gameObject);

        //得到模型最长端作为计算视点距离
        if (maxX > maxY)
        {
            maxNum = maxX;
        }
        else
        {
            maxNum = maxY;
        }
        if (maxNum < 5) maxNum = 5;
        //获得模型正前方视点
        Camera.main.transform.position = new Vector3(centerPoint.x, centerPoint.y, centerPoint.z - maxNum);
        
//================================================
//方法二:如果obj对象为静态对象,则用此方法
        //Renderer[] mrs = obj.GetComponentsInChildren<Renderer>();
        //Vector3 center = obj.transform.position;
        //if (mrs.Length != 0)
        //{
        //    Bounds bounds = new Bounds(center, Vector3.zero);
        //    foreach (Renderer item in mrs)
        //    {
        //        bounds.Encapsulate(item.bounds);
        //    }
        //    center = bounds.center;
        //    print("中心点:" + center + "最大点:" + bounds.max + "最小点:" + bounds.min);

        //    if ((bounds.max.x - bounds.min.x) > (bounds.max.y - bounds.min.y))
        //    {
        //        maxNum = bounds.max.x - bounds.min.x;
        //    }else if((bounds.max.x - bounds.min.x) < (bounds.max.y - bounds.min.y))
        //    {
        //        maxNum = bounds.max.y - bounds.min.y;
        //    }
        //    else
        //    {
        //        maxNum = bounds.max.x - bounds.min.x;
        //    }
        //    print(maxNum);
        //    //限制模型过小,导致定位过近
        //    if (maxNum < 8)
        //    {
        //        maxNum = 8;
        //    }
        //    print(maxNum);
        //}
        //centerPoint = center;
//================================================

        //高亮
        Highlighter highlighter = obj.gameObject.AddComponent<Highlighter>();//添加高亮脚本
        highlighter.ConstantOn();

      
    }

    // Update is called once per frame
    void Update()
    {
        //拖动
        if (Input.GetMouseButton(2))
        {
            //根据距离实时调节拖动灵敏度
            MovingSpeed = Vector3.Distance(transform.position, centerPoint) / 40;
            
            delta_x = Input.GetAxis("Mouse X") * MovingSpeed;
            delta_y = Input.GetAxis("Mouse Y") * MovingSpeed;
            //rotation = Quaternion.Euler(0, transform.rotation.eulerAngles.y, 0);
            //transform.position = rotation * new Vector3(-delta_x, 0, -delta_y) + transform.position;
            transform.Translate(-delta_x, -delta_y, 0);


        }

        //缩放
        if (Input.GetAxis("Mouse ScrollWheel") != 0)
        {
            //缩放距离限制
            if(Vector3.Distance(transform.position, centerPoint) < 5f)
            {
                delta_z = -Input.GetAxis("Mouse ScrollWheel") * ZoomSpeed;
                if (delta_z > 0)
                {
                    transform.Translate(0, 0, -delta_z);
                }
            }else if (Vector3.Distance(transform.position, centerPoint) > maxNum*2f)
            {
                delta_z = -Input.GetAxis("Mouse ScrollWheel") * ZoomSpeed;
                if (delta_z < 0)
                {
                    transform.Translate(0, 0, -delta_z);
                }
            }
            else
            {
                delta_z = -Input.GetAxis("Mouse ScrollWheel") * ZoomSpeed;
                transform.Translate(0, 0, -delta_z);
            }
            

        }

        //旋转
        if (Input.GetMouseButton(1))
        {
            //根据距离调节旋转灵敏度
            //RotateSpeed = Vector3.Distance(transform.position, centerPoint) / 80;

            delta_rotation_x = Input.GetAxis("Mouse X") * RotateSpeed;
            delta_rotation_y = -Input.GetAxis("Mouse Y") * RotateSpeed;
            position = transform.rotation * new Vector3(0, 0, distance) + transform.position;
            transform.Rotate(0, delta_rotation_x, 0, Space.World);
            transform.Rotate(delta_rotation_y, 0, 0);
            transform.position = transform.rotation * new Vector3(0, 0, -distance) + position;
            
            
        }
    }


    /// <summary>
    /// 获得中心点
    /// </summary>
    /// <param name="target"></param>
    /// <returns></returns>
    private Vector3 GetCenter(GameObject target)
    {
        Renderer[] mrs = target.GetComponentsInChildren<Renderer>();
        Vector3 center = target.transform.position;
        if (mrs.Length != 0)
        {
            Bounds bounds = new Bounds(center, Vector3.zero);
            foreach (Renderer item in mrs)
            {
                bounds.Encapsulate(item.bounds);
            }
            center = bounds.center;
        }
        return center;
    }
}

 

2013-11-12 17:42:29 s10141303 阅读数 7166

实现鼠标旋转拖动缩放模型,非常不错的代码:

using UnityEngine;
using System.Collections;

public class MouseControl : MonoBehaviour
{

    //目标物体
    public Transform target;
    private int MouseWheelSensitivity = 1; //放大倍数的快慢
    private int MouseZoomMin = 1; //最小倍数
    private int MouseZoomMax = 5; //最大倍数
    //默认距离
    private float normalDistance = 3;


    private Vector3 normalized;

    //拖拽的移动速度
    private float xSpeed = 250.0f;
    private float ySpeed = 120.0f;

    //拖拽的高度限制
    private int yMinLimit = -20;
    private int yMaxLimit = 80;

    //角度
    private float x = 0.0f;
    private float y = 0.0f;
    
    //记录目标物体的坐标
    private Vector3 screenPoint;
    private Vector3 offset;

    //围绕x旋转30°
    private Quaternion rotation = Quaternion.Euler(new Vector3(30f, 0f, 0f));

    //目标的3D坐标
    private Vector3 CameraTarget;

    //打印欧拉角:绕各个轴旋转的角度,顺时针为正方向
    public void Awake()
    {
        print(transform.eulerAngles.x);
        print(transform.eulerAngles.y);
        print(transform.eulerAngles.z);
    }

    void Start()
    {
        //找到目标飞机的3d坐标
        CameraTarget = target.position;

        //目标飞机的z-3,距离摄像机更近了
        float z = target.transform.position.z - normalDistance;
        //给当前相机给定位,现在的3D坐标乘以30°
        transform.position = rotation * new Vector3(transform.position.x, transform.position.y, z);

        //将视角转向物体
        transform.LookAt(target);

        //记录各个轴偏离的角度
        var angles = transform.eulerAngles;
        x = angles.y;
        y = angles.x;
    }

    void OnGUI()
    {
        GUI.Label(new Rect(10,10,300,30),"左击:旋转;滚轮:缩放;中击:拖拽");
    }

    void Update()
    {
        //如果左击了,旋转
        if (Input.GetMouseButton(0))
        {
            x += Input.GetAxis("Mouse X") * xSpeed * 0.02f;
            y -= Input.GetAxis("Mouse Y") * ySpeed * 0.02f;

            y = ClampAngle(y, yMinLimit, yMaxLimit);

            var rotation = Quaternion.Euler(y, x, 0);
            var position = rotation * new Vector3(0.0f, 0.0f, -normalDistance) + CameraTarget;

            transform.rotation = rotation;
            transform.position = position;

        }
        //滚轮缩放
        else if (Input.GetAxis("Mouse ScrollWheel") != 0)
        {
            //摄像机3d坐标-物体的3d坐标
            normalized = (transform.position - CameraTarget).normalized;

            if (normalDistance >= MouseZoomMin && normalDistance <= MouseZoomMax)
            {
                normalDistance -= Input.GetAxis("Mouse ScrollWheel") * MouseWheelSensitivity;
            }
            if (normalDistance < MouseZoomMin)
            {
                normalDistance = MouseZoomMin;
            }
            if (normalDistance > MouseZoomMax)
            {
                normalDistance = MouseZoomMax;
            }
            //改变摄像机的远近
            transform.position = normalized * normalDistance;
        }
        //案件按下 记录鼠标的
        else if (Input.GetMouseButtonDown(2))
        {
            //将目标物体的坐标转化成平面坐标
            screenPoint = Camera.main.WorldToScreenPoint(target.transform.position);
            //计算鼠标的3维坐标跟物体的3维坐标的差值
            offset = target.transform.position - Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z));
        }

        //中键拖拽,改变飞机的坐标,每帧调用
        if (Input.GetMouseButton(2))
        {
            //鼠标的平面坐标
            Vector3 curScreenPoint = new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z);
            //鼠标转移的3d空间坐标值
            Vector3 curPosition = Camera.main.ScreenToWorldPoint(curScreenPoint) + offset;
            //改变鼠标的3D空间坐标
            target.transform.position = curPosition;
        }
        //朝向,每动一帧都要改变朝向
        transform.LookAt(CameraTarget);
    }

    //控制旋转的角度,如果旋转的角度大于360或者小于360都要加上或者减去对应的角度
    static float ClampAngle(float angle, float min, float max)
    {
        if (angle < -360)
            angle += 360;
        if (angle > 360)
            angle -= 360;
        return Mathf.Clamp(angle, min, max);
    }
}




没有更多推荐了,返回首页