[当存在许多具有相同标签的对撞机时,是否只能访问一个对撞机?

问题描述 投票:0回答:2

我有一个脚本,它将脚本中的对象移动到手指的位置,它基于标签,因此当我用标签触摸对象时,所有具有相同标签的对象都将移动到该位置。有没有办法让我感动的人动起来?

脚本

 {
     void FixedUpdate()
     {
         if (Input.touchCount > 0)
         {            
             RaycastHit2D hitInformation = Physics2D.Raycast(Camera.main.ScreenToWorldPoint(Input.GetTouch(0).position),Camera.main.transform.forward);            
                 if (hitInformation.collider.gameObject.tag == "RocketPrefab")
                 {                    
                     Vector3 touchPosition = Camera.main.ScreenToWorldPoint(Input.GetTouch(0).position);
                     touchPosition.z = -4;
                     transform.position = touchPosition;
                     Debug.Log(touchPosition);

                 }                            
         }
     }
 } ```

c# unity3d tags raycasting
2个回答
2
投票

您可以使用hitInformation.collider.gameObject访问Raycast正在触摸的对象。

从我看到的代码中,我认为这应该起作用:

     void FixedUpdate()
     {
         if (Input.touchCount > 0)
         {            
             RaycastHit2D hitInformation = Physics2D.Raycast(Camera.main.ScreenToWorldPoint(Input.GetTouch(0).position),Camera.main.transform.forward);            
                 if (hitInformation.collider.gameObject.tag == "RocketPrefab")
                 {                    
                     Vector3 touchPosition = Camera.main.ScreenToWorldPoint(Input.GetTouch(0).position);
                     touchPosition.z = -4;
                     hitInformation.collider.gameObject.transform.position = touchPosition;
                     Debug.Log(touchPosition);
                 }                            
         }
     }

0
投票

[我假设脚本位于所有“ RocketPrefab” GameObjects的父级上,然后将其全部移到transform.position = touchPosition;行中>

基于这种假设...要获得射线广播命中的特定信号,您需要编辑脚本以移动collider.gameObjct.transform而不仅仅是transform

已编辑的FixedUpdate

void FixedUpdate()
{
    if (Input.touchCount > 0)
    {            
        RaycastHit2D hitInformation = Physics2D.Raycast(Camera.main.ScreenToWorldPoint(Input.GetTouch(0).position),Camera.main.transform.forward);            
        if (hitInformation.collider.gameObject.tag == "RocketPrefab")
        {                    
            Vector3 touchPosition = Camera.main.ScreenToWorldPoint(Input.GetTouch(0).position);
            touchPosition.z = -4;
            hitInformation.collider.gameObject.transform.position = touchPosition; // Note this line and how it targets the specific transform
            Debug.Log(touchPosition);
        }                            
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.