Unity面試上機題之鼠標拖動物體和滾輪縮放

創建DragCube腳本掛載在Cube上
代碼如下

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


public class DragCube: MonoBehaviour
{
    private Camera cam;//發射射線的攝像機
    private GameObject go;//射線碰撞的物體
    public static string btnName;//射線碰撞物體的名字
    private Vector3 screenSpace;
    private Vector3 offset;
    private bool isDrage = false;
    
    Vector3 scale;
    void Start()
    {
        cam = Camera.main;
        scale = gameObject.transform.localScale;
    }

    void Update()
    {
        //整體初始位置 
        Ray ray = cam.ScreenPointToRay(Input.mousePosition);
        //從攝像機發出到點擊座標的射線
        RaycastHit hitInfo;


        if (isDrage == false)
        {
            if (Physics.Raycast(ray, out hitInfo))
            {
                //劃出射線,只有在scene視圖中才能看到
                Debug.DrawLine(ray.origin, hitInfo.point);
                go = hitInfo.collider.gameObject;
                //print(btnName);
                screenSpace = cam.WorldToScreenPoint(go.transform.position);
                offset = go.transform.position - cam.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenSpace.z));
                //物體的名字  
                btnName = go.name;
                //組件的名字


            }
            else
            {
                btnName = null;
            }


        }


        if (Input.GetMouseButton(0))
        {
            Vector3 currentScreenSpace = new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenSpace.z);
            Vector3 currentPosition = cam.ScreenToWorldPoint(currentScreenSpace) + offset;


            if (btnName != null)
            {
                go.transform.position = currentPosition;
            }



            isDrage = true;
        }
        else
        {
            isDrage = false;
        }
        if (Input.GetAxis("Mouse ScrollWheel") < 0)
        {
            //if (Camera.main.fieldOfView <= 100)
            //    Camera.main.fieldOfView += 2;
            
            if (scale.x<5)
            {
                scale.x += 0.2f;
                scale.y += 0.2f;
                scale.z += 0.2f;
                gameObject.transform.localScale = scale;
            }
        }
        //Zoom in
        if (Input.GetAxis("Mouse ScrollWheel") > 0)
        {
            //縮放攝像機視角fieldOfView值
            //if (Camera.main.fieldOfView > 40)
            //    Camera.main.fieldOfView -= 2;
            //縮放物體
            if (scale.x > 0)
            {
                scale.x -= 0.2f;
                scale.y -= 0.2f;
                scale.z -= 0.2f;
                gameObject.transform.localScale = scale;
            }

        }

    }

    




}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章