c# - 统一点击检测游戏对象

标签 c# android unity3d touch detect

<分区>

我目前正在制作一款足球游戏。

在这个小游戏中,当玩家触球时,会增加力量,目标是获得更高的分数。

所以我写道:

 void Update()
{
    if(Input.touchCount == 1 && Input.GetTouch(0).phase== TouchPhase.Began)
      {
       AddForce, and playsound ect...
      }

}

有了这个,当我触摸屏幕上的任何地方时,它会增加力量,但我只想在触摸我的游戏对象(球)时增加力量。

我该怎么做?

谢谢! :)

最佳答案

With this, when i touch anywhere on the screen, it adds force, but i just want to add force when i touch my gameobject (the ball).

要检测对特定游戏对象的点击,您必须使用 Raycast 来检测对该足球的点击。只需确保碰撞器(例如 Sphere Collider)附加到它即可。

void Update()
{
    if ((Input.touchCount > 0) && (Input.GetTouch(0).phase == TouchPhase.Began))
    {
        Ray raycast = Camera.main.ScreenPointToRay(Input.GetTouch(0).position);
        RaycastHit raycastHit;
        if (Physics.Raycast(raycast, out raycastHit))
        {
            Debug.Log("Something Hit");
            if (raycastHit.collider.name == "Soccer")
            {
                Debug.Log("Soccer Ball clicked");
            }

            //OR with Tag

            if (raycastHit.collider.CompareTag("SoccerTag"))
            {
                Debug.Log("Soccer Ball clicked");
            }
        }
    }
}

关于c# - 统一点击检测游戏对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38565746/

相关文章:

android - 键盘隐藏输入(位置:fixed; bottom:0;) with phonegap on android

c# - 将 html 转换为 MSWord

c# - 将 JSON 文件传递​​给 Javascript ASP.NET MVC4

android - ListView长按动画

android - 扩展 AdapterView

firebase - Cocoapods Firebase pod 更新

java - 获取有效的 JNIEnv 指针

c# - 重力和向心力

c# - Telegram Bot Api 库 (.Net) 中标题的换行符

c# - 使用 PayPal Checkout Express 时是否可以通过 SetExpressCheckout 传递送货地址?