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

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

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

[unity3d]屏幕坐标跟世界坐标的转换_第1张图片
代码挂在摄像机上:
using UnityEngine;
using System.Collections;

public class cameramove : MonoBehaviour
{

    private Vector3 world;

    private float speed = 0;//物体移动的速度

    // Use this for initialization
    void Start()
    {
        world.x = -2;
        world.y = 0;
        world.z = 6;
    }

    // Update is called once per frame
    void Update()
    {
        Vector2 screenpos = Camera.main.WorldToScreenPoint(transform.position);//物体的世界坐标转化成屏幕坐标
        Vector3 e = Input.mousePosition;//鼠标的位置

        
        //当点击鼠标中键时

        if (Input.GetMouseButtonDown(2))
        {
            //e.z=screenpos.z;//1.因为鼠标的屏幕 Z 坐标的默认值是0,所以需要一个z坐标
            //e.z=1;//将鼠标
            //摄像机要垂直于x-z平面
            //world=Camera.main.ScreenToWorldPoint(e);
            world = new Vector3(Input.mousePosition.x/Screen.width,Input.mousePosition.y/Screen.height,106f );
            Vector3 world1= Camera.main.ViewportToWorldPoint(new Vector3(world.x, world.y, 106f));
            //world.x = Camera.main.ScreenToWorldPoint(Input.mousePosition).x;
            //world.z = Camera.main.ScreenToWorldPoint(Input.mousePosition).y;
            //world.y = transform.position.y;

            print("new x:" + world.x);
            print("new y:" + world.y);
            print("new z:" + world.z);

            //创建物体
            //GameObject goNew = GameObject.CreatePrimitive(PrimitiveType.Sphere);
            //goNew.transform.position = world1;
            transform.LookAt(world1);
        }
    }
}

==================== 迂者 丁小未 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

你可能感兴趣的:([unity3d]屏幕坐标跟世界坐标的转换)