Unity鼠标控制3D物体的移动、旋转、缩放

一、鼠标控制3D物体移动

1.使用协程

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

public class ControlMove : MonoBehaviour
{
    Vector3 cubeScreenPos;
    Vector3 offset;

    void Start()
    {
        StartCoroutine(OnMouseDown());//在Start方法中调用StartCoroutine(要调用的协程方法)
    }

    //协程
    IEnumerator OnMouseDown()
    {
        //1. 得到物体的屏幕坐标
        cubeScreenPos = Camera.main.WorldToScreenPoint(transform.position);

        //2. 计算偏移量
        //鼠标的三维坐标
        Vector3 mousePos = new Vector3(Input.mousePosition.x, Input.mousePosition.y, cubeScreenPos.z);
        //鼠标三维坐标转为世界坐标
        mousePos = Camera.main.ScreenToWorldPoint(mousePos);
        offset = transform.position - mousePos;

        //3. 物体随着鼠标移动
        while (Input.GetMouseButton(0))
        {
            //目前的鼠标二维坐标转为三维坐标
            Vector3 curMousePos = new Vector3(Input.mousePosition.x, Input.mousePosition.y, cubeScreenPos.z);
            //目前的鼠标三维坐标转为世界坐标
            curMousePos = Camera.main.ScreenToWorldPoint(curMousePos);

            //物体世界位置
            transform.position = curMousePos + offset;
            yield return new WaitForFixedUpdate(); //这个很重要,循环执行
        }
    }
}

2.鼠标左键控制物体移动,鼠标碰到物体,物体颜色改变

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

public class TransformModel : MonoBehaviour
{
    //鼠标经过时改变物体颜色
    private Color mouseOverColor = Color.blue;//声明变量为蓝色
    private Color originalColor;//声明变量来存储本来颜色

    void Start()
    {
        originalColor = GetComponent<Renderer>().sharedMaterial.color;//开始时得到物体着色
    }

    void OnMouseEnter()
    {
        GetComponent<Renderer>().material.color = mouseOverColor;//当鼠标滑过时改变物体颜色为蓝色
    }

    void OnMouseExit()
    {
        GetComponent<Renderer>().material.color = originalColor;//当鼠标滑出时恢复物体本来颜色
    }

    IEnumerator OnMouseDown()
    {
        Vector3 screenSpace = Camera.main.WorldToScreenPoint(transform.position);//三维物体坐标转屏幕坐标
        //将鼠标屏幕坐标转为三维坐标,再计算物体位置与鼠标之间的距离
        var offset = transform.position - Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenSpace.z));
        
        while (Input.GetMouseButton(0))
        {
            //将鼠标位置二维坐标转为三维坐标
            Vector3 curScreenSpace = new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenSpace.z);
            //将鼠标转换的三维坐标再转换成世界坐标+物体与鼠标位置的偏移量
            var curPosition = Camera.main.ScreenToWorldPoint(curScreenSpace) + offset;
            transform.position = curPosition;
            yield return new WaitForFixedUpdate();//循环执行
        }
    }
}

二、鼠标控制3D物体旋转

1. 控制物体左右旋转,上下旋转
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class TransformModel : 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(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;
        }
    }

    //角度范围值限定
    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);
    }
}
2. 控制摄像机以物体为中心旋转

脚本挂载到摄像机上

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

public class TransformModel : MonoBehaviour
{
    public Transform CenObj;//围绕的物体
    private Vector3 Rotion_Transform;
    private new Camera camera;
    void Start()
    {
        camera = GetComponent<Camera>();
        Rotion_Transform = CenObj.position;
    }
    void Update()
    {
        Ctrl_Cam_Move();
        Cam_Ctrl_Rotation();
    }
    //镜头的远离和接近
    public void Ctrl_Cam_Move()
    {
        if (Input.GetAxis("Mouse ScrollWheel") > 0)
        {
            transform.Translate(Vector3.forward * 1f);//速度可调  自行调整
        }
        if (Input.GetAxis("Mouse ScrollWheel") < 0)
        {
            transform.Translate(Vector3.forward * -1f);//速度可调  自行调整
        }
    }
    //摄像机的旋转
    public void Cam_Ctrl_Rotation()
    {
        var mouse_x = Input.GetAxis("Mouse X");//获取鼠标X轴移动
        var mouse_y = -Input.GetAxis("Mouse Y");//获取鼠标Y轴移动
        if (Input.GetKey(KeyCode.Mouse1))
        {
            transform.RotateAround(Rotion_Transform, Vector3.up, mouse_x * 5);
            transform.RotateAround(Rotion_Transform, transform.right, mouse_y * 5);
        }
    }
}

三、鼠标控制3D物体缩放

1. 基于物体本身的Transform的缩放
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class TransformModel : MonoBehaviour
{
    //缩放比例限制
    public float MinScale = 0.2f;
    public float MaxScale = 3.0f;
    //缩放比例
    private float scale = 1.0f;


    void Update()
    {
        if (Input.GetAxis("Mouse ScrollWheel") != 0)
        {
            scale += Input.GetAxis("Mouse ScrollWheel");
            scale = Mathf.Clamp(scale, MinScale, MaxScale);
            transform.localScale = new Vector3(scale, scale, scale);
        }
    }
}
2. 基于摄像机的远近的缩放

脚本挂载到摄像机上

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

public class TransformModel : MonoBehaviour
{
    void Update()
    {
        if (Input.GetAxis("Mouse ScrollWheel") != 0)
        {
            //鼠标滚动滑轮 值就会变化
            if (Input.GetAxis("Mouse ScrollWheel") < 0)
            {
                //范围值限定
                if (Camera.main.fieldOfView <= 100)//摄像机采用Perspective透视
                    Camera.main.fieldOfView += 2;
                if (Camera.main.orthographicSize <= 20)//摄像机采用Orthograpic正交
                    Camera.main.orthographicSize += 0.5F;
            }
            //Zoom in  
            if (Input.GetAxis("Mouse ScrollWheel") > 0)
            {
                //范围值限定
                if (Camera.main.fieldOfView > 2)//摄像机采用Perspective透视
                    Camera.main.fieldOfView -= 2;
                if (Camera.main.orthographicSize >= 1)//摄像机采用Orthograpic正交
                    Camera.main.orthographicSize -= 0.5F;
            }
        }
    }
}
  • 20
    点赞
  • 227
    收藏
    觉得还不错? 一键收藏
  • 6
    评论
要实现在 Unity 中使用鼠标控制物体旋转移动,你可以使用以下示例代码: ```csharp using UnityEngine; public class MouseControl : MonoBehaviour { private Vector3 mouseOrigin; private bool isRotating; private bool isMoving; private bool isScaling; void Update() { // 鼠标右键按下时旋转物体 if (Input.GetMouseButtonDown(1)) { mouseOrigin = Input.mousePosition; isRotating = true; } // 鼠标右键松开时停止旋转 if (Input.GetMouseButtonUp(1)) { isRotating = false; } // 鼠标中键按下时移动物体 if (Input.GetMouseButtonDown(2)) { mouseOrigin = Input.mousePosition; isMoving = true; } // 鼠标中键松开时停止移动 if (Input.GetMouseButtonUp(2)) { isMoving = false; } // 鼠标滚轮滚动时物体 float scroll = Input.GetAxis("Mouse ScrollWheel"); if (scroll != 0f) { isScaling = true; } else { isScaling = false; } if (isRotating) { // 根据鼠标移动旋转物体 Vector3 mouseOffset = (Input.mousePosition - mouseOrigin) * 0.1f; transform.Rotate(mouseOffset.y, -mouseOffset.x, 0, Space.World); mouseOrigin = Input.mousePosition; } if (isMoving) { // 根据鼠标移动移动物体 Vector3 mouseOffset = (Input.mousePosition - mouseOrigin) * 0.01f; transform.Translate(mouseOffset.x, mouseOffset.y, 0, Space.World); mouseOrigin = Input.mousePosition; } if (isScaling) { // 根据鼠标滚轮的滚动来物体 float scaleAmount = 1f + scroll; transform.localScale *= scaleAmount; } } } ``` 将以上代码添加到一个物体上,然后在场景中将需要控制物体作为该物体的子物体。在运行游戏时,你可以使用鼠标右键来旋转物体,使用鼠标中键来移动物体,使用鼠标滚轮来物体

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值