[unity3d]屏幕坐标跟世界坐标的转换

keep study very day!写写今天的学习收获,今天学习到了平面坐标跟世界坐标的相互转换。

效果:点击鼠标中键,创建一个小球,虽然看起来是屏面的,但实则是在三维空间里面创建的哦!


代码挂在摄像机上:
[csharp]  view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  1. using UnityEngine;  
  2. using System.Collections;  
  3.   
  4. public class cameramove : MonoBehaviour  
  5. {  
  6.   
  7.     private Vector3 world;  
  8.   
  9.     private float speed = 0;//物体移动的速度  
  10.   
  11.     // Use this for initialization  
  12.     void Start()  
  13.     {  
  14.         world.x = -2;  
  15.         world.y = 0;  
  16.         world.z = 6;  
  17.     }  
  18.   
  19.     // Update is called once per frame  
  20.     void Update()  
  21.     {  
  22.         Vector2 screenpos = Camera.main.WorldToScreenPoint(transform.position);//物体的世界坐标转化成屏幕坐标  
  23.         Vector3 e = Input.mousePosition;//鼠标的位置  
  24.   
  25.           
  26.         //当点击鼠标中键时  
  27.   
  28.         if (Input.GetMouseButtonDown(2))  
  29.         {  
  30.             //e.z=screenpos.z;//1.因为鼠标的屏幕 Z 坐标的默认值是0,所以需要一个z坐标  
  31.             //e.z=1;//将鼠标  
  32.             //摄像机要垂直于x-z平面  
  33.             //world=Camera.main.ScreenToWorldPoint(e);  
  34.             world = new Vector3(Input.mousePosition.x/Screen.width,Input.mousePosition.y/Screen.height,106f );  
  35.             Vector3 world1= Camera.main.ViewportToWorldPoint(new Vector3(world.x, world.y, 106f));  
  36.             //world.x = Camera.main.ScreenToWorldPoint(Input.mousePosition).x;  
  37.             //world.z = Camera.main.ScreenToWorldPoint(Input.mousePosition).y;  
  38.             //world.y = transform.position.y;  
  39.   
  40.             print("new x:" + world.x);  
  41.             print("new y:" + world.y);  
  42.             print("new z:" + world.z);  
  43.   
  44.             //创建物体  
  45.             //GameObject goNew = GameObject.CreatePrimitive(PrimitiveType.Sphere);  
  46.             //goNew.transform.position = world1;  
  47.             transform.LookAt(world1);  
  48.         }  
  49.     }  
  50. }  

==================== 迂者 丁小未 CSDN博客专栏=================

MyBlog:http://blog.csdn.net/dingxiaowei2013             MyQQ:1213250243

Unity QQ群:858550         cocos2dx QQ群:280818155

====================== 相互学习,共同进步 ===================

转载请注明出处:http://blog.csdn.net/dingxiaowei2013/article/details/14498293

欢迎关注我的微博: http://weibo.com/u/2590571922
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值