unity 鼠标控制object 旋转 放大缩小 移动

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

public class MouseMoveandScaleRotation : MonoBehaviour {

    ///旋转速度,需要调试
    public float xSpeed = 250.0f;
    public float ySpeed = 130.0f;
    //限制旋转角度,物体绕x轴旋转限制,不能上下颠倒。
    public float yMinLimit = -30;
    public float yMaxLimit = 30;
    //物体的旋转角度
    public float x = 0.0f;
    public float y = 0.0f;


    private Vector3 targetScreenpos;//拖拽物体的屏幕坐标
    private Vector3 targetWorldpos;//拖拽物体的世界坐标
    private Transform target;//拖拽物体
    private Vector3 mouseScreenpos;//鼠标的屏幕坐标
    private Vector3 offset;//偏移量
    Color oricolor = Color.black;//物体本来的颜色

    void Start() {

        //初始化旋转角度,记录开始时物体的旋转角度。
        Vector3 angels = transform.eulerAngles;
        x = angels.y;
        y = angels.x;

        target = transform;
    }

    void Update() {

        if (Input.GetMouseButton(1)) {
            //鼠标沿x轴的移动乘以系数当作物体绕y轴的旋转角度。
            //鼠标沿y轴的移动乘以系数当作物体绕x轴的旋转角度。
            x += Input.GetAxis("Mouse X") * xSpeed * 0.02f;
            y += Input.GetAxis("Mouse Y") * ySpeed * 0.02f;
        }

        Camera.main.fieldOfView = Camera.main.fieldOfView + Input.GetAxis("Mouse ScrollWheel") * -20;
    }

    /* void OnMouseEnter()
     {
         //当鼠标在物体上时,改变物体颜色。
         GetComponent<Renderer>().material.color = Color.blue;
     }
     void OnMouseExit()
     {
         GetComponent<Renderer>().material.color = oricolor;
     }*/

    //被移动物体需要添加collider组件,以响应OnMouseDown()函数
    //基本思路。当鼠标点击物体时(OnMouseDown(),函数体里面代码只执行一次),记录此时鼠标坐标和物体坐标,并求得差值。如果此后用户仍然按着鼠标左键,那么保持之前的差值不变即可。
    //由于物体坐标是世界坐标,鼠标坐标是屏幕坐标,需要进行转换。具体过程如下所示。
    IEnumerator OnMouseDown() {
        targetScreenpos = Camera.main.WorldToScreenPoint(target.position);
        mouseScreenpos = new Vector3(Input.mousePosition.x, Input.mousePosition.y, targetScreenpos.z);
        offset = target.position - Camera.main.ScreenToWorldPoint(mouseScreenpos);

        while (Input.GetMouseButton(0))//鼠标左键被持续按下。
        {
            mouseScreenpos = new Vector3(Input.mousePosition.x, Input.mousePosition.y, targetScreenpos.z);
            targetWorldpos = Camera.main.ScreenToWorldPoint(mouseScreenpos) + offset;
            target.position = targetWorldpos;
            yield return new WaitForFixedUpdate();
        }
    }

    void LateUpdate() {
        //限制绕x轴的移动。
        y = Mathf.Clamp(y, yMinLimit, yMaxLimit);
        Quaternion rotation = Quaternion.Euler(y, -x, 0);
        transform.rotation = rotation;
    }
}

注意:物体必须添加刚体组件!!!!

来自https://blog.csdn.net/weixin_37921492/article/details/78493209?utm_medium=distribute.pc_relevant.none-task-blog-baidujs-3

猜你喜欢

转载自www.cnblogs.com/zqiang0803/p/12971854.html