如何在Unity中查找2D游戏对象的长度

时间:2014-03-26 01:45:38

标签: unity3d 2d

我想要一个绝对的初学者的答案,如何使用Unity找到2D游戏对象的长度/高度。我试图弄清楚玩家是否点击了这个对象,如下所示:

using UnityEngine;
using System.Collections;

public class LoadNewGame : MonoBehaviour {
    //Objects
    Touch t;
    GameObject g;
    //Coords
    int touchX;
    int touchY;
    int objectX;
    int objectY;
    //Size
    //int sizex
    //int sizey

    //Initialization
    void Start () {
        //Touch
        t = Input.GetTouch;

        //Object Position
        objectX = g.transform.position.x;
        objectY = g.transform.position.y;
        //initialize sizex and sizey
    }

    //Clickity Click Click
    void Update () {
        touchX = t.position.x;
        touchY = t.position.y;
        //If the player clicked on the object
        if(touchX <= objectX && 
           touchY <= objectY &&
           //touchX => objectX + sizeX &&
           //touchY => objectY + sizeY
           ){
            //Do Stuff
        }


    }
}

无论是否有更简单的方法来查找他们是否触摸过图像(但请告诉我),我想知道如果它再次出现,如何计算出物体的高度和长度。谢谢!

1 个答案:

答案 0 :(得分:1)

基本上你可以做的是根据鼠标坐标在场景中拍摄光线,然后报告光线与光线碰撞的任何物体

试试这个:

RaycastHit2D hit = Physics2D.Raycast(Camera.main.ScreenToWorldPoint(Input.mousePosition), Vector2.zero);

if(hit.collider != null)
{

    Debug.Log ("Target Position: " + hit.collider.gameObject.transform.position);

}

Reference