Home > Blockchain >  What is wrong with this raycast?
What is wrong with this raycast?

Time:03-31

I'm using the same raycast in the code for picking up and dropping. When i have the item at the cursor, at the first time he hits the square under it. When i pick it again and want to drop it on the same place he hits only the item and not the square under it. I don't get this, as the item has the same position at the cursor both times.

if (Input.GetMouseButtonDown(0)) {
   Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
   RaycastHit hit;
   if (Physics.Raycast(ray, out hit)) {
      Debug.Log(hit.transform.name);
   }
}

Output:

Diamond(Clone)
UnityEngine.Debug:Log (object)
ColorLogic:checkMouseClick () (at Assets/Scripts/ColorLogic.cs:97)
ColorLogic:Update () (at Assets/Scripts/ColorLogic.cs:30)

Square_3_10
UnityEngine.Debug:Log (object)
ColorLogic:checkMouseClick () (at Assets/Scripts/ColorLogic.cs:97)
ColorLogic:Update () (at Assets/Scripts/ColorLogic.cs:30)

Diamond(Clone)
UnityEngine.Debug:Log (object)
ColorLogic:checkMouseClick () (at Assets/Scripts/ColorLogic.cs:97)
ColorLogic:Update () (at Assets/Scripts/ColorLogic.cs:30)

Diamond(Clone)
UnityEngine.Debug:Log (object)
ColorLogic:checkMouseClick () (at Assets/Scripts/ColorLogic.cs:97)
ColorLogic:Update () (at Assets/Scripts/ColorLogic.cs:30)

See Video: https://drive.google.com/file/d/1S8iF3gYcMDmo1WwZlb1H21d-n8cTn2R-/view?usp=sharing

CodePudding user response:

First, the behaviour is due to the fact that the ray hits all collider on the scene and puts the first hit info into the RaycastHit.

There are several ways to accomplish this.

  1. Use a layer mask
  2. Disable the collider when the diamond is dropped (but you'd like to drag and drop again, don't you?

The first one is the best so define a LayerMask and process it into your logic after the diamond is dropped.

int squareMask = 10;
int maxDistance = 100;
if (Physics.Raycast(ray, out hit, maxDistance, squareMask)) {
    // process here
}
  • Related