unity3d点击图片放大

2019-10-05 10:44:49 qq_36907428 阅读数 484
  • Unity 值得看的500+ 技术内容列表

    Unity3D是由Unity Technologies开发的一个让玩家轻松创建诸如三维视频游戏、建筑可视化、实时三维动画等类型互动内容的多平台的综合型游戏开发工具,是一个全面整合的专业游戏引擎。


        在某些特定情况下,有时候我们需要放大缩小一张背景图片。最方便的做法就是:只需要通过鼠标和滚轮就能随意对Unity中导入的背景图片在鼠标位置进行放大缩小操作。 


     思路和代码如下。

    首先加载缓存中的图片给Image:

1、加载图片并抛出

 public static IEnumerator loadPicture(string absPath, Action<Sprite> callback)
    {
        WWW www = new WWW(absPath);
        yield return www;
        if (string.IsNullOrEmpty(www.error))
        {
            Sprite sprite = CreateSprite(www.texture);

            if (callback != null)
            {
                callback(sprite);
            }
        }
        else
        {

            Debug.Log(www.error);
        }
    }

 /// <summary>
    /// 创建精灵图片
    /// </summary>
    /// <param name="texture"></param>
    /// <returns></returns>
    public static Sprite CreateSprite(Texture2D texture)
    {
        if (!texture)
        {
            return null;
        }
        return Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), new Vector2(0.5f, 0.5f));

2、设置图片给image 

public void LoadPicture(string bgpath)
        {
            if (string.IsNullOrEmpty(bgpath))
            {
                return;
            }
            string absPath = "file:///" + bgpath;
            StartCoroutine(FileUtils.loadPicture(absPath, sprite =>
            {
                img_Background.GetComponent<Image>().sprite = sprite;

            }));
        }

        /// <summary>
        ///3、使用滑轮  根据鼠标位置 设置背景板的背景大小
        /// </summary>
        public void SetImageSize(Transform transform)
        {
            float value = 0;
            value = controller.inputControl.MouseScrollWheel;
            if (value == 0)
            {
                return;
            }
            SetMouseChangeForImage(transform, value > 0 ? stepValue : -stepValue);
        }

 /// <summary>
        /// 4、通过鼠标控制缩放比例
        /// </summary>
        /// <param name="transform"></param>
        /// <param name="value"></param>
       void SetMouseChangeForImage(Transform transform,int value)
        {
            float delX = Input.mousePosition.x - transform.position.x;
            float delY = Input.mousePosition.y - transform.position.y;

            float scaleX = delX / transform.GetComponent<RectTransform>().rect.width / transform.localScale.x;
            float scaleY = delY / transform.GetComponent<RectTransform>().rect.height / transform.localScale.y;

            transform.GetComponent<RectTransform>().localScale += Vector3.one * 0.1f * value;
            nowVector3 = transform.GetComponent<RectTransform>().localScale;
            if (nowVector3.x < 0.1f)
            {
                transform.GetComponent<RectTransform>().localScale = Vector3.one * 0.1f;
            }
            if (nowVector3.x>3f)
            {
                transform.GetComponent<RectTransform>().localScale = Vector3.one * 3f;
            }
            transform.GetComponent<RectTransform>().pivot += new Vector2(scaleX, scaleY);
            transform.GetComponent<RectTransform>().anchoredPosition3D += new Vector3(delX, delY, 0);
        }

    }

2016-06-07 08:15:04 yangmeng13930719363 阅读数 4240
  • Unity 值得看的500+ 技术内容列表

    Unity3D是由Unity Technologies开发的一个让玩家轻松创建诸如三维视频游戏、建筑可视化、实时三维动画等类型互动内容的多平台的综合型游戏开发工具,是一个全面整合的专业游戏引擎。

目标
下面的示例代码的主要目的是为了解释如何在 Unity 中实现缩放即以点击屏幕的功能。

1. 介绍

在示例代码中,实现了放大或缩小和点击功能。在手机的图库中,缩放和平移/拖动图像时,它具有相同的行为。此示例代码对 unity2d 和 unity3d 对象都起作用。它独立于摄像机;无论主摄像机是 tk2d 摄像机简单的摄像机以及它的投影类型是正交或是透视

2. 例子Example

下面的 c# 代码实现的是,你可以通过两个手指来放大和缩小屏幕以及在图片上点击移动。

注意
在你想要实现缩放功能的游戏物体上添加下面的脚本。

2.1 PinchZoomScript

using UnityEngine;
using System.Collections;

public class PinchZoom : MonoBehaviour
{
    private float scale_factor= 0.07f;  
    private float MAXSCALE = 6.0f, MIN_SCALE = 0.6f; // zoom-in and zoom-out limits
    private bool isMousePressed;
    private Vector2 prevDist = new Vector2(0,0);
    private Vector2 curDist = new Vector2(0,0);
    private Vector2 midPoint = new Vector2(0,0);
    private Vector2 ScreenSize;
    private Vector3 originalPos;
    private GameObject parentObject;

    void Start ()
    {
        // Game Object will be created and make current object as its child (only because we can set virtual anchor point of gameobject and can zoom in and zoom out from particular position)
        parentObject = new GameObject("ParentObject");
        parentObject.transform.parent = transform.parent;
        parentObject.transform.position = new Vector3(transform.position.x*-1, transform.position.y*-1, transform.position.z);
        transform.parent = parentObject.transform;

        ScreenSize = Camera.main.ScreenToWorldPoint(new Vector2(Screen.width,Screen.height));
        originalPos = transform.position;
        isMousePressed = false;
    }
    void Update ()
    {
        if(Input.GetMouseButtonDown(0))
            isMousePressed = true;
        else if(Input.GetMouseButtonUp(0))
            isMousePressed = false;
        // These lines of code will pan/drag the object around untill the edge of the image
        if(isMousePressed && Input.touchCount==1 && Input.GetTouch(0).phase == TouchPhase.Moved && (parentObject.transform.localScale.x > MIN_SCALE || parentObject.transform.localScale.y > MIN_SCALE))
        {
            Touch touch = Input.GetTouch(0);    
            Vector3 diff = touch.deltaPosition*0.1f;    
            Vector3 pos = transform.position + diff;
            if(pos.x > ScreenSize.x * (parentObject.transform.localScale.x-1))
                pos.x = ScreenSize.x * (parentObject.transform.localScale.x-1);
            if(pos.x < ScreenSize.x * (parentObject.transform.localScale.x-1)*-1)
                pos.x = ScreenSize.x * (parentObject.transform.localScale.x-1)*-1;
            if(pos.y > ScreenSize.y * (parentObject.transform.localScale.y-1))
                pos.y = ScreenSize.y * (parentObject.transform.localScale.y-1);
            if(pos.y < ScreenSize.y * (parentObject.transform.localScale.y-1)*-1)
                pos.y = ScreenSize.y * (parentObject.transform.localScale.y-1)*-1;
            transform.position = pos;
        }
        // On double tap image will be set at original position and scale
        else if(Input.touchCount==1 && Input.GetTouch(0).phase == TouchPhase.Began && Input.GetTouch(0).tapCount==2)
        {
            parentObject.transform.localScale = Vector3.one;
            parentObject.transform.position = new Vector3(originalPos.x*-1, originalPos.y*-1, originalPos.z);
            transform.position = originalPos;
        }    
        checkForMultiTouch();
    }
    // Following method check multi touch
    private void checkForMultiTouch()
    {
        // These lines of code will take the distance between two touches and zoom in - zoom out at middle point between them
        if (Input.touchCount == 2 && Input.GetTouch(0).phase == TouchPhase.Moved && Input.GetTouch(1).phase == TouchPhase.Moved)
        {
            midPoint = new Vector2(((Input.GetTouch(0).position.x + Input.GetTouch(1).position.x)/2), ((Input.GetTouch(0).position.y + Input.GetTouch(1).position.y)/2));
            midPoint = Camera.main.ScreenToWorldPoint(midPoint);

            curDist = Input.GetTouch(0).position - Input.GetTouch(1).position; //current distance between finger touches
            prevDist = ((Input.GetTouch(0).position - Input.GetTouch(0).deltaPosition) - (Input.GetTouch(1).position - Input.GetTouch(1).deltaPosition)); //difference in previous locations using delta positions
            float touchDelta = curDist.magnitude - prevDist.magnitude;
            // Zoom out
            if(touchDelta>0)
            {
                if(parentObject.transform.localScale.x < MAXSCALE && parentObject.transform.localScale.y < MAXSCALE)
                {
                    Vector3 scale = new Vector3(parentObject.transform.localScale.x + scale_factor, parentObject.transform.localScale.y + scale_factor, 1);
                    scale.x = (scale.x > MAXSCALE) ? MAXSCALE : scale.x;
                    scale.y = (scale.y > MAXSCALE) ? MAXSCALE : scale.y;
                    scaleFromPosition(scale,midPoint);
                }
            }
            //Zoom in
            else if(touchDelta<0)
            {
                if(parentObject.transform.localScale.x > MIN_SCALE && parentObject.transform.localScale.y > MIN_SCALE)
                {
                    Vector3 scale = new Vector3(parentObject.transform.localScale.x + scale_factor*-1, parentObject.transform.localScale.y + scale_factor*-1, 1);
                    scale.x = (scale.x < MIN_SCALE) ? MIN_SCALE : scale.x;
                    scale.y = (scale.y < MIN_SCALE) ? MIN_SCALE : scale.y;
                    scaleFromPosition(scale,midPoint);
                }
            }
        }
        // On touch end just check whether image is within screen or not
        else if (Input.touchCount == 2 && (Input.GetTouch(0).phase == TouchPhase.Ended || Input.GetTouch(0).phase == TouchPhase.Canceled || Input.GetTouch(1).phase == TouchPhase.Ended || Input.GetTouch(1).phase == TouchPhase.Canceled))
        {
            if(parentObject.transform.localScale.x < 1 || parentObject.transform.localScale.y < 1)
            {
                parentObject.transform.localScale = Vector3.one;
                parentObject.transform.position = new Vector3(originalPos.x*-1, originalPos.y*-1, originalPos.z);
                transform.position = originalPos;
            }
            else
            {
                Vector3 pos = transform.position;
                if(pos.x > ScreenSize.x * (parentObject.transform.localScale.x-1))
                    pos.x = ScreenSize.x * (parentObject.transform.localScale.x-1);
                if(pos.x < ScreenSize.x * (parentObject.transform.localScale.x-1)*-1)
                    pos.x = ScreenSize.x * (parentObject.transform.localScale.x-1)*-1;
                if(pos.y > ScreenSize.y * (parentObject.transform.localScale.y-1))
                    pos.y = ScreenSize.y * (parentObject.transform.localScale.y-1);
                if(pos.y < ScreenSize.y * (parentObject.transform.localScale.y-1)*-1)
                    pos.y = ScreenSize.y * (parentObject.transform.localScale.y-1)*-1;
                transform.position = pos;
            }
        }
    }
    //Following method scales the gameobject from particular position
    static Vector3 prevPos = Vector3.zero;
    private void scaleFromPosition(Vector3 scale, Vector3 fromPos)
    {
        if(!fromPos.Equals(prevPos))
        {
            Vector3 prevParentPos = parentObject.transform.position;
            parentObject.transform.position = fromPos;    
            Vector3 diff = parentObject.transform.position - prevParentPos;
            Vector3 pos = new Vector3(diff.x/parentObject.transform.localScale.x*-1, diff.y/parentObject.transform.localScale.y*-1, transform.position.z);
            transform.localPosition = new Vector3(transform.localPosition.x + pos.x, transform.localPosition.y+pos.y, pos.z);
        }
        parentObject.transform.localScale = scale;
        prevPos = fromPos;
    }
}

如果你查到了任何关于如何在 Unity 2D 和 3D 中缩放以及点击屏幕?,请提交你的问题,我们会尽力解决它。

有了一个游戏开发的主意?你还在等什么?现在就联系我们吧!你会看到这个想法很快就实现了。我们的公司被看作是在印度最好的游戏开发公司之一

原帖地址

2018-06-12 11:40:08 linuxheik 阅读数 6746
  • Unity 值得看的500+ 技术内容列表

    Unity3D是由Unity Technologies开发的一个让玩家轻松创建诸如三维视频游戏、建筑可视化、实时三维动画等类型互动内容的多平台的综合型游戏开发工具,是一个全面整合的专业游戏引擎。

首先,是要新建一个UIRoot(使用的NGUI开发),因为一个项目中有时候往往一个UIRoot无法搞定,需要分割出一部分进行单独的处理,所以大家要视情况而定。 

复制代码
using UnityEngine;
using System.Collections;
       
public class Minimap : MonoBehaviour {
       
    public Camera minimapCamera;
    public float minfiledView = 44f;
    public float maxfiledView = 95f;
    private Vector3 offsetPosition;
       
    void Start () {
       
    }
           
    // Update is called once per frame
    void Update () {
        
    }
       
    public void ZoomInButtonClick()
    {
        if (minimapCamera.fieldOfView > minfiledView)
        {
            minimapCamera.fieldOfView -= 1;
        }
        else
            minimapCamera.fieldOfView = minfiledView; 
    }
       
    public void ZoomOutButtonClick()
    {
        if (minimapCamera.fieldOfView < maxfiledView)
        {
            minimapCamera.fieldOfView += 1;
        }
        else
            minimapCamera.fieldOfView = maxfiledView;
    }
}
此处的代码构思来源于小地图的制作,通过控制fieldOfView来确定Camera的视野大小,大家也可以设定视野的范围,让他在指定区间内变化。 

接下来是要对图片的动态载入 


复制代码
using UnityEngine;
using System.Collections;
using System.IO;
using System;
using System.Drawing;
       
public class OpenPicture : MonoBehaviour
{ 
    public Texture2D _texture;
    public GameObject DaYangTu;
       
    IEnumerator Open()
    {
        string path = Application.persistentDataPath + "/Image" + "/placeholder.jpg";
        WWW www = new WWW("file://" + path);
        yield return www;
        Debug.Log(":" + www.error);
        _texture = new Texture2D(300, 300);
        _texture = www.texture;
        DaYangTu.GetComponent<UITexture>().mainTexture = _texture;
    }
       
    public void OnClick()
    {
        DaYangTu.SetActive(true);
        StartCoroutine(Open());
    }
    // Update is called once per frame
    void Update () {
           
    }
}
此处我使用的是使用WWW加载本地指定路径的文件,发布后可以更换图片,但名字要保持不变。 
最后是实现对图片的拖拽浏览,就是给你被拖拽的对象添加一个UI Drag Object脚本,注意不要忘记给被拖拽对象加Box Collider.
2014-06-25 15:03:00 u010841622 阅读数 2042
  • Unity 值得看的500+ 技术内容列表

    Unity3D是由Unity Technologies开发的一个让玩家轻松创建诸如三维视频游戏、建筑可视化、实时三维动画等类型互动内容的多平台的综合型游戏开发工具,是一个全面整合的专业游戏引擎。

using UnityEngine;
using System.Collections;

public class DParaticle : MonoBehaviour {
	
	//摄像机
	public GameObject camera_1;
	Vector3 p;
	Quaternion r;
	Vector3 s;

	//目标物体
	public GameObject target1, target2, target3, target4, target5;
	bool target1Bool,target2Bool,target3Bool,target4Bool,target5Bool;

	void Start () {
		//保存摄像机初始位置
		p=camera_1.transform.position;
		r=camera_1.transform.rotation;
		s=camera_1.transform.localScale;
	}

	void Update () {
		if(Input.GetMouseButton(0)){
			Ray ray = camera_1.camera.ScreenPointToRay(Input.mousePosition);
			RaycastHit hit;
			if(Physics.Raycast(ray,out hit)){
				if(hit.collider.gameObject==target1){
					if (!target1Bool) {
						camera_1.transform.LookAt(target1.transform);
						camera_1.camera.orthographicSize=3.0f;
					}else{
						first ();
					}
					target1Bool =! target1Bool;
				}else if(hit.collider.gameObject==target2){
					if(!target2Bool){
						//camera_1.transform.LookAt(target2.transform);
						camera_1.camera.orthographicSize=3.0f;
					}else{
						first ();
					}
					target2Bool=!target2Bool;
				}else if(hit.collider.gameObject==target3){
					if(!target3Bool){
						camera_1.transform.LookAt(target3.transform);
						camera_1.camera.orthographicSize=3.0f;
					}else{
						first ();
					}
					target3Bool=!target3Bool;
				}else if(hit.collider.gameObject==target4){
					if(!target4Bool){
						camera_1.transform.LookAt(target4.transform);
						camera_1.camera.orthographicSize=3.0f;
					}else{
						first ();
					}
					target4Bool=!target4Bool;
				}else if(hit.collider.gameObject==target5){
					if(!target5Bool){
						camera_1.transform.LookAt(target5.transform);
						camera_1.camera.orthographicSize=3.0f;
					}else{
						first ();
					}
					target5Bool=!target5Bool;
				}
			}
		}
	}

	void first () {
		camera_1.transform.position=p;
		camera_1.transform.rotation=r;
		camera_1.transform.localScale=s;
		camera_1.camera.orthographicSize=13.1f;
	}
}


源代码是可以运行的,但我优化了下源代码,然后脚本没有测试过。

2018-03-26 20:27:51 xing920312 阅读数 1087
  • Unity 值得看的500+ 技术内容列表

    Unity3D是由Unity Technologies开发的一个让玩家轻松创建诸如三维视频游戏、建筑可视化、实时三维动画等类型互动内容的多平台的综合型游戏开发工具,是一个全面整合的专业游戏引擎。

1. js代码部分放于页脚HTML代码

<script type="text/javascript">
    var contextPath = "${request.contextPath}";
    $(document).ready(function() {
  //图片放大  
   $("#outerdiv").hide();
   $(function(){  
   $("img").mouseover(function(){
       $(this).css("cursor","pointer");
   });
 
   $("img").click(function(){  
       var _this = $(this);//将当前的pimg元素作为_this传入函数    
       imgShow("#outerdiv", "#bigimg", _this);    
     });     
   });    
 
   function imgShow(outerdiv, bigimg, _this){  
       var src = _this.attr("src");//获取当前点击的pimg元素中的src属性    
       $('#outerdiv').attr('display','block');  
       $(bigimg).attr("src", src);//设置#bigimg元素的src属性    
        $(outerdiv).fadeIn("fast");  
        
   $(outerdiv).click(function(){//再次点击淡出消失弹出层    
       $(this).fadeOut("fast");    
   }); 
   }  
});
 
    </script>

2. html代码部分也放于页脚HTML代码

<div id="outerdiv" style="text-align: center;position: fixed;z-index: 1000;top: 0;left: 0; width: 100%;height: 100%;background-color: rgba(255,255,255,.9);">

   <img id="bigimg" style="height: auto;width: 46.6325%;border: 0; margin: auto;position: absolute;top: 0;bottom: 0;left: 0;right: 0;" src="" />

</div>

说明:用于查看图片,查看用户图片或物品图片详情及审核图片等

Unity3D常见面试题

阅读数 38542