Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 12 Next capture
2021 2022 2023
1 capture
12 Jun 22 - 12 Jun 22
sparklines
Close Help
  • 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
0
Question by FlyingFlambe · Sep 15, 2016 at 04:11 AM · gameobjectraycastmousepositionraycasthit2dgame object

How do I move only one selected object, rather than all objects with that script?

Been looking at a number of tutorials and forum questions, but I haven't been able to find the right answer to this one yet.

I'm working on a game where the level is filled with movable objects that can be translated up or down by the player. When the movement script is placed on one object and mouse click, it works the way it should. But if I put the script in all objects that need it and mouse click over an object, it moves all objects simultaneously. I'd imagine that raycasting is necessary, but I'm not too sure how to go about it in this case. Here's the current script:

     void Update()
     {
         if (Input.GetMouseButtonDown(0))
         {
             GetComponent<Rigidbody2D>().velocity = new Vector2(0, forceInstant);
         }
 
         if (Input.GetMouseButtonDown(1))
         {
             GetComponent<Rigidbody2D>().velocity = new Vector2(0, -forceInstant);
         }
     }

Sorry if this seems like a dumb question; still learning Unity & C# so please forgive me if this has a simple solution (I'll probably be on here a lot). Thank you!

Comment
Add comment
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

3 Replies

· Add your reply
  • Sort: 
avatar image
1

Answer by iabulko · Sep 15, 2016 at 06:25 AM

Raycasting isn't so hard as you imagine ;). Do not add script to all of the objects, just add it to one (i.e. called MainScripts ;p)

 if (Input.GetMouseButton (0))
 {
     Vector2 mousePosition = Input.mousePosition;
     RaycastHit hit;
 
     Ray ray = Camera.main.ScreenPointToRay(mousePosition);
 
     if(Physics.Raycast(ray, out hit, float.MaxValue))
     {
         actuallyHandledTra = hit.transform.GetComponent<Rigidbody2D>().velocity = new Vector2(0, forceInstant);
     }
 }
Comment
Add comment · 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
0

Answer by FlyingFlambe · Sep 16, 2016 at 11:36 AM

Thank you @iabulko! I had to fiddle with a few things since it's 2D not 3D, but I was curious on how to add the script to MainScripts and load it from there, rather than adding it to the object. Here's the current code as it is now (descriptions are there for clarity on my own part):

     void Update()
     {    
         //Instant force.
         if (Input.GetMouseButtonDown(0))
         {
             //Creates a vector that holds location of the mouse pointer.
             Vector2 mousePosition = Input.mousePosition;
             //Creates a raycasthit variable to detect when mousePosition hits an object.
             RaycastHit2D hit = Physics2D.Raycast(Camera.main.ScreenToWorldPoint(Input.mousePosition), Vector2.zero);
 
             //If the hit ray hits an object's collider...
             if (hit.collider != null)
             {
                 //Add forceInstant to the gameObject.
                 hit.collider.gameObject.transform.GetComponent<Rigidbody2D>().velocity = new Vector2(0, forceInstant);
             }
         }

With the way it is right now, it moves only one object (which is what I wanted!), but it's able to move any object with a Rigidbody2D, including the player object. How would I use something like CompareTag to only move objects with that specific tag? (Also, should I ask this question on a different post next time? :x) Again, your response helped me a lot. Thank you!

Comment
Add comment · Show 3 · 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 iabulko · Sep 22, 2016 at 08:14 AM 0
Share

You can always check it by name or tag

 //If the hit ray hits an object's collider...
              if (hit.collider != null)
              {
                  //Add forceInstant to the gameObject.
                  if(hit.collider.gameObject.CompareTag("ObjectTagThatINeedToClick"))
                  hit.collider.gameObject.transform.GetComponent<Rigidbody2D>().velocity = new Vector2(0, forceInstant);
              }
avatar image FlyingFlambe iabulko · Sep 25, 2016 at 07:59 AM 0
Share

Thank you! Was trying to figure out how to format the CompareTag part but kept getting it wrong, so that helped a good bit. :)

avatar image piyushaggarwal1011 · Jul 30, 2018 at 11:12 AM 0
Share

Thanks FlyingFlambe, I was trying this since past 6 hrs and your code really helped me. (Tu khuda ka baccha hai (God's child)!!!)

avatar image
0

Answer by Adarn · Sep 16, 2016 at 01:47 AM

An alternative to using a ray cast is the OnMouseDown() from monoBehaviouor

https://docs.unity3d.com/ScriptReference/MonoBehaviour.OnMouseDown.html

So a quick solution would be to change

 void Update()

to

  void OnMouseDown()

This way you can put your script on all the objects you want this behaviour on (like you already have done), but it only gets called on the objects you actually click on.

The body of your function should be okay as is, but you may need to change it slightly if you want it to run if the mouse button is held. I think this function only fires for the on press.

Comment
Add comment · 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 FlyingFlambe · Sep 21, 2016 at 09:16 PM 0
Share

Thanks @Adarn. Using On$$anonymous$$ouseDown() would likely be useful in most cases, but been trying it out and doesn't seem to do what it needs to, since there's a few mouse commands that overlap (more explained at the end).

The main issue that needs to be fixed now is to not move just any rigidbody-- while this script exist in the game object its supposed to pertain to. With how it is right now, if I put the script on the correct object, the force command in that script can be applied to any object with a rigidbody which is kind of strange.

I'll also ask this part in another question later since its off-topic (and because its not really working right), but for clarity's sake on why On$$anonymous$$ouseDown() won't work too well: the game makes heavy use of the mouse buttons so the big issue right now is how the mouse commands overlap one another. Here's how I'm currently trying to set them up:

  • [Standard Force - Up] Left click (held down): applies an upward s$$anonymous$$dy acceleration via incremental additive force

  • [Standard Force - Down] Right click (held down): applies a downward s$$anonymous$$dy acceleration via incremental additive force

  • [Instant Force - Up] Left click (release): applies an upward high-impact force via one-time force + current velocity

  • [Instant Force - Down] Right click (release): applies a downward high-impact force via one-time force + current velocity

Hopefully that gives some insight on my current issue. I appreciate the feedback!

avatar image FlyingFlambe · Sep 21, 2016 at 09:21 PM 0
Share

Oh, I also just caught this. When I try to run the build, it creates tens (or hundreds) of the same error saying the script is trying to access objects without a rigidbody. So something strange is definitely going on that I can't figure out.

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.

Follow this Question

Answers Answers and Comments

6 People are following this question.

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

Related Questions

Hit is always returning null for some reason. 1 Answer

2D - finding object at mouse position 2 Answers

Dynamic mesh positioning with Raycast intersection... 0 Answers

Raycasting2D to Compare Tag of GameObject 1 Answer

Raycast Not Working 3 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