Home > Software design >  2D Object Not Detecting When Hit by Raycast
2D Object Not Detecting When Hit by Raycast

Time:09-10

I'm creating a top down 2D game, where the player has to break down trees. I made it so the player casts a ray toward the mouse, and when the ray hits a tree, it should lower the tree's health. I don't get any errors when I run the game or click, but it seems like the tree isn't detecting the hits.

void Update()
{
...
if (Input.GetMouseButtonDown(0))
        {
            RaycastHit2D hit = Physics2D.Raycast(playerRb.transform.position, mousePosition - playerRb.transform.position, 2.0f);

            if (hit.collider != null)
            {
                if (hit.collider == GameObject.FindWithTag("Tree"))
                {
                    hit.collider.GetComponent<TreeScript>().treeHealth--;
                }
            }
        }
}

Still pretty new to coding and I'm teaching myself, so please make your answer easy to understand to help me learn.

CodePudding user response:

Input.mousePosition is equal to the pixel your mouse is on. This is very different than the location your mouse is pointing at in the scene. To explain further, Input.mousePosition is where the mouse is. Think about it. If the camera was facing up, the mouse positon would be the same, but where they are clicking is different.

Instead of using Input.mousePosition, You should pass this into a function called Ray Camera.ScreenPointToRay();

You just input the mouse position and then use this new ray to do the raycast.

ANOTHER EXTREMELY IMPORTANT THING 1: Do not use Camera.main in Update(), as it uses a GetComponet call, which can cause perormance decreases. Store a reference of it in your script and use that.

Extremely important thing 2: I notice you are using GetComponent to change the tree's health. This is fine, but do not use GetComponent if you don't have to.

Like this:

Camera cam;
void Start()
{
   cam = Camera.main; //it is fine to use this in start,
                 //because it is only being called once.
}
void Update()
{
...
if (Input.GetMouseButtonDown(0))
        {
            Ray ray = cam.ScreenPointToRay(Input.mousePosition);
            RaycastHit2D hit = Physics2D.Raycast(ray);
            ...
        }
}

CodePudding user response:

You need to convert your mouse position from screen point to world point with Z value same as the other 2D objects.

Vector3 Worldpos=Camera.main.ScreenToWorldPoint(mousePos);

Also use a Debug.DrawRay to check the Raycast

Debug.DrawRay(ray.origin, ray.direction*10000f,Color.red);

Source

  • Related