Raycasting to find mouseclick on Object in unity 2d games

前端 未结 4 1351
猫巷女王i
猫巷女王i 2021-02-04 13:10

I am trying to delete the object on which the mouse is clicked. I am making a 2D game using the new Unity3D 4.3. Here is the code I\'m using

void Update () {

           


        
4条回答
  •  感动是毒
    2021-02-04 14:00

    This question is a bit old, but I was looking for a a way to get a GameObject with a mouse click in unity 2D, and the Answer from Esa almost helped me, but I couldn't afford to make it to work, so with a bit of research I saw that Camera.main.ScreenToWorldPoint was returning the center of the screen area of the Camera and to it work right. it required to enter the difference in Z position from the camera and the nearest GameObject. My Camera was set by default in -10 and my GameObject was in 0, so all I needed to do is set my Input.mousePosition.z to 10. So if you are getting problem to work with Esa's code (like me :( )the code bellow may help you:

    RaycastHit2D hit = Physics2D.Raycast(Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, 10)), Vector2.zero);
    
    if(hit.collider != null)
    {
        Debug.Log ("Target Position: " + hit.collider.gameObject.transform.position);
    }
    

提交回复
热议问题