Unity - 点击Gameobject中心获取本地鼠标位置

时间:2015-04-27 13:23:58

标签: unity3d raycasting mouse-position

我想从游戏对象的中心点击鼠标点击位置,比如说一个Sphere of Scale(1,1,1)。如果我点击球体的中心,它应该将x分量返回为零,在点击球体的最左边时,它应该返回-0.5作为vector3的x分量,并且在点击球体的最右边时返回0.5 。以下代码帮助我在原点实现这一目标。但是,它有一个约束。球体必须定位在(0,任何东西,任何东西)(因为我关心的是x轴)。 关于如何在不考虑球体位置的情况下实现这一目标的任何帮助?

bool isGameOver = false;
float pointX;

// Update is called once per frame
void Update () {
    if(!isGameOver){
        RaycastHit hit;
        if(Input.GetMouseButtonDown(0)){
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            if(Physics.Raycast(ray, out hit)){
                if(hit.transform.tag =="Ball"){
                    pointX = transform.InverseTransformPoint(hit.point).x;
                }
            }
        }
    }
}

3 个答案:

答案 0 :(得分:1)

您使用的是透视相机还是ortographic? 如果您使用透视并将游戏对象移动到右侧,则无法击中右侧的0.5。因为它隐藏在球的可见部分。 只能使用orto相机

答案 1 :(得分:0)

你的代码没问题。 如果你需要对象位置,只需要将transform.localposition添加到你的pointX。

String expected String = "/Company Home/IRP/tranzycja";

String actual_String = driver.findElement(By.xpath("//span[@class='alfresco-renderers-PropertyLink alfresco-renderers-Property pointer small']//span[@class='value']")).getText();

if(expected String.equals(actual_String))

{

System.out.println("Text is Matched");

}

else

{

System.out.println("Text is not Matched");

}

答案 2 :(得分:0)

使用此代码旋转您的游戏对象,寻找相机,您现在可以获得所需的正确x坐标。

void Update () {
    if(!isGameOver)
    {
        Vector3 offset =  transform.position - Camera.main.transform.position;
        transform.LookAt(transform.position + offset);
        RaycastHit hit;
        if(Input.GetMouseButtonUp(0)){
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            if(Physics.Raycast(ray, out hit)){
                if(hit.transform.tag =="Ball")
                {

                    pointX = hit.transform.InverseTransformPoint(hit.point);
                    Debug.Log ("X:" + pointX.ToString());
                }
            }
        }
    }
}