Home > Net >  Input.GetMouseButton(0) and RaycastHit2D hit are effecting multiple objects instead of just the one
Input.GetMouseButton(0) and RaycastHit2D hit are effecting multiple objects instead of just the one

Time:07-14

I'm trying to differentiate my clicks per each individual item but I can't seem to figure this out. I want to click and then have the item I'm clicking on rotate but all of the items rotate. Here's my code:

      {
          if (Input.GetMouseButton(0))
          {
              Ray ray = loadCam.ScreenPointToRay(Input.mousePosition);
              RaycastHit2D hit = Physics2D.Raycast(ray.origin, ray.direction, Mathf.Infinity, draggableLayers);


              if (hit)
              {
                  holdDownTime  = 1 * Time.deltaTime;
              }

                      if (hit && holdDownTime >= 0.5f)
                      {
                          Vector3 direction = new Vector3(0, 0, 0);
                          Quaternion targetRotation = Quaternion.Euler(direction);
                          rb.transform.rotation = Quaternion.RotateTowards(transform.rotation, targetRotation, Time.deltaTime * 500f);
                      }
                  }

        if (Input.GetMouseButtonUp(0))
        {
            holdDownTime = 0;
        }

              }

CodePudding user response:

Use the Physics2D.RayCastAll() to get all the ray Hits , then check if the hit collider is equals your target object , if yes then do the rotation.

CodePudding user response:

I figured out a way to this: on a separate GameObject, I detect the click and fill an empty static GameObject "container" on the physics 2D "hit". On the actual GameObject I want to rotate, I check to see if on GetMouseButton if the object is = to the static container object. Then allow the rotation. Works perfectly.

  • Related