• Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
Question by Fadi · Dec 16, 2013 at 07:15 PM · 2dphysicslayersselect

Select 2D Object By Mouse ?

Hi ...

I'm trying to make a 2D Game but I have this problem ...

How can I select the character by clicking on it ?

Note :

  • I've 3 Layers ( Background , Characters , Objects )

  • In 3D game I can use ( ray , RaycastHit and Physics ) to do that , but I tried to convert it to 2D , but it doesn't work ...

Please how can I do that ?

Comment
ludvicktoba

People who like this

1 Show 0
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

4 Replies

· Add your reply
  • Sort: 
avatar image
Best Answer

Answer by Spinnernicholas · Dec 16, 2013 at 11:20 PM

This will return a 2D collider at the current mouse position. It works by calculating the 2D position of the mouse from the Orthographic camera. Then, doing a 2d raycast with a single point(zero length), but infinite depth(distance from camera). This works because Physics2D.Raycast() can return colliders that the ray begins inside.

 Physics2D.Raycast(position, direction, length);

Here:

 Physics2D.Raycast(new Vector2(camera.ScreenToWorldPoint(Input.mousePosition).x,camera.ScreenToWorldPoint(Input.mousePosition).y), Vector2.Zero, 0f);


[OLD]:

Don't forgot to use Physics2D.Raycast().

Comment
ZenithCode
Homletmoo
Nikunj-Kareliya
FlightOfOne
Hilfor
JamesBrodski
Hokto
Bob-The-Zealot
wmadwand
kdeger
kodo91
DaniilGalahow
Mnemotic
cidp
torleone
And 1 more...

People who like this

16 Show 5 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image Spinnernicholas · Dec 17, 2013 at 06:50 PM 1
Share

Updated Answer.

avatar image Fadi · Dec 17, 2013 at 09:18 PM 2
Share

this is the full code ^_^

     var hit: RaycastHit2D = Physics2D.Raycast(Vector2(camera.ScreenToWorldPoint(Input.mousePosition).x,camera.ScreenToWorldPoint(Input.mousePosition).y), Vector2.zero, 0);

thank you soooooooooooo much :)

avatar image FlightOfOne · Nov 01, 2015 at 10:51 PM 2
Share

Thank you, Spinnernicholas! this helped me.

Here is the c# full method:

   //This method returns the game object that was clicked using Raycast 2D
    GameObject ClickSelect()
     {
        //Converting Mouse Pos to 2D (vector2) World Pos
        Vector2 rayPos = new Vector2(Camera.main.ScreenToWorldPoint(Input.mousePosition).x, Camera.main.ScreenToWorldPoint(Input.mousePosition).y);
        RaycastHit2D hit=Physics2D.Raycast(rayPos, Vector2.zero, 0f);
         
         if (hit)
         {
              Debug.Log(hit.transform.name);
             return hit.transform.gameObject;
         }
         else return null;
     }





avatar image foxthib FlightOfOne · Feb 12, 2016 at 06:04 PM 0
Share

I try this and that didn't work. I create a Debug.Ray but nothing appear. I also try to configure the mini and max depth (0 and infinity) for the same result. Some idea ?

avatar image emred111 FlightOfOne · Nov 13, 2020 at 01:58 PM 0
Share

thanks dude :) post it as comment

avatar image

Answer by robertbu · Dec 16, 2013 at 11:45 PM

There are three ways for you to solve your problem:

1) Use as script with an OnMouseDown() function attached to each selectable object. OnMouse* functions work with both 2D and 3D colliders.

2) Use a 3D collider on a child object. You cannot have a 2D and a 3D collider on the same object, but you can have an empty game object as a child of your sprite with its own collider. You'll need to pick and size the collider as appropriate to your sprite. You can use the transform.parent of the child object if you need to get access to the sprite and/or its scripts. You would use the original Physics.Raycast().

3) Here is a hack I discovered yesterday. First convert your mouse position into a world coordinate using Camera.ScreenToWorldPoint(). Then use that position to do a Physics2D.Raycast() with a very short ray (like 0.05). It does matter what direction, but the distance needs to be short.

Comment
Nikunj-Kareliya

People who like this

1 Show 2 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image Fadi · Dec 17, 2013 at 07:43 AM 0
Share

thank you . the first and second are a good solutions , but I need to select it by raycast this code I use for 3D , How can I convert it to 2D ?

     var ray : Ray = Camera.main.ScreenPointToRay(Input.mousePosition);
     var hit : RaycastHit;
     if(Physics.Raycast(ray,hit))
         print(hit.collider.gameObject.name);

thanks ...

avatar image robertbu · Dec 17, 2013 at 02:44 PM 0
Share

That's solution #2:

  • Add an empty child game object to your 2D object at the same position (i.e. local position (0,0,0).

  • Add a collider such as a box collider to the empty game object.

  • Size the collider to fit the 2D object

If you want to output the name of the 2D object, then the last line would be:

 print(hit.transform.parent.name);
avatar image

Answer by MFen · Dec 16, 2013 at 07:22 PM

pseudo code

 if (Input.GetMouseButtonDown(0) && myPlayerRect.Contains(Input.mousePosition))
     {
          //I've clicked on the player
     }
Comment

People who like this

0 Show 0 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image

Answer by j_pablo_gn · Oct 01, 2016 at 04:27 PM

This works for me by attaching the script to the main camera (Orthographic). It is based on Spinnernicholas solution.

     // Update is called once per frame
     void Update () {

         if (Input.GetMouseButtonDown(0))
         {
             Vector2 origin = new Vector2(Camera.main.ScreenToWorldPoint(Input.mousePosition).x,
                                          Camera.main.ScreenToWorldPoint(Input.mousePosition).y);
             RaycastHit2D hit = Physics2D.Raycast(origin, Vector2.zero, 0f);
             if (hit) {
                 print(hit.transform.gameObject.tag);
             }
         }
     }
Comment

People who like this

0 Show 0 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Welcome to Unity Answers

If you’re new to Unity Answers, please check our User Guide to help you navigate through our website and refer to our FAQ for more information.

Before posting, make sure to check out our Knowledge Base for commonly asked Unity questions.

Check our Moderator Guidelines if you’re a new moderator and want to work together in an effort to improve Unity Answers and support our users.

Follow this Question

Answers Answers and Comments

26 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

Lights that ignore position.z of GameObject 0 Answers

How do I use layermasks? 9 Answers

Sucking a zero-gravity ship into a black hole. 1 Answer

BoxCollider2Ds overlap each other 0 Answers

How to make correct double jump with collor changing? 0 Answers


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges