简体   繁体   中英

Raycast not detecting colliders

So I'm working on a little top-down perspective game and wanted to add a combat system. I set it up so that it'll shoot a raycast and if it hits an enemy they'll take damage but the raycast is returning nothing.

Vector3 mouse_pos = Input.mousePosition;
mouse_pos.z = 5.23f;

Vector3 objectPos = Camera.main.WorldToScreenPoint(transform.position);
mouse_pos.x = mouse_pos.x - objectPos.x
mouse_pos.y = mouse_pos.y - objectPos.y

if (Input.GetMouseButtonDown(0))
{
    Raycast hit;
    print(Physics.Raycast(transform.position, mouse_pos, out hit));
    if (Physics.Raycast(transform.position, mouse_pos, out hit))
    {
        if (hit.collider.gameObject.name.Contains("enemy"))
        {
            hit.collider.gameObject.GetComponent<enemyMovement>().life -= 1;
        }
    }
}

The print returns false even when there's a gameobject there. It's probably a simple problem but I don't know what to do lol.

I changed the code for you, because I am not very familiar with the ray, thank you and hope it can help you.

   void update(){
        if (Input.GetMouseButtonDown(0))
      {
        // When the left mouse button is pressed, emit a ray to the screen 
         position where the mouse is located
         Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
         RaycastHit hitInfo;  
       if (Physics.Raycast(ray,out hitInfo))
       {
            // When the ray collides with the object, draw the ray in the scene view
            Debug.DrawLine(ray.origin, hitInfo.point, Color.red);  
        
        if (hitInfo.collider.gameObject.name.Contains("enemy"))
        {
            hitInfo.collider.gameObject.GetComponent<enemyMovement>().life -= 1;
          }
      }
   }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM