Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 13 Next capture
2021 2022 2023
1 capture
13 Jun 22 - 13 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 Ochreous · Sep 23, 2014 at 05:43 AM · c#gameobjectraycast

C# Raycast 2D GameObject follow Mouse

I'm trying to get a Gameobject that is found by my RaycastHit2D to follow my mouse while I hold down the left mouse button. The Raycast is hitting the Gameobject because the debug.log pops up. But for some reason the Gameobject isn't following my mouse. It works fine when directly attaching a script to the Gameobject without using a raycast like the following below.

     void LateUpdate ()
     {        
         Vector3 mousePositions = new Vector3(transform.position.x + Input.mousePosition.x/sensitivity,transform.position.y + Input.mousePosition.y/sensitivity,transform.position.z);
         if (Input.GetMouseButtonDown (0)){
         Debug.Log ("Target Position: " + hit.collider.gameObject.transform.position);
         transform.position = Vector3.Lerp(transform.position, mousePositions, Time.smoothDeltaTime/sensitivity);
         }
     }

So I'm not entirely sure what's wrong with my current script. It's an exact copy of the above same but with some raycasting modifications. I tried hit.collider.Gameobject instead of just hit but that didn't seem to make a difference.

    void LateUpdate () {
         Vector3 pos = Camera.main.ScreenToWorldPoint (Input.mousePosition);
         RaycastHit2D hit = Physics2D.Raycast(pos, transform.position);
         Debug.DrawLine(Vector2.zero, pos, Color.cyan);
         if (hit.collider != null) {
         if(Input.GetMouseButtonDown (0)){
         Debug.Log ("Target Position: " + hit.collider.gameObject.transform.position);
         Vector3 mousePositions = new Vector3(hit.transform.position.x + Input.mousePosition.x/sensitivity,hit.transform.position.y + Input.mousePosition.y/sensitivity,hit.transform.position.z);
         hit.transform.position = Vector3.Lerp(hit.transform.position, pos, Time.smoothDeltaTime/sensitivity);
             }
         }
     }




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

1 Reply

· Add your reply
  • Sort: 
avatar image
2

Answer by HarshadK · Sep 23, 2014 at 05:55 AM

Since you are moving the gameobject using Vector3.Lerp it will actually not be present under your mouse which is what causing the problem.

 GameObject gameObjectToMove;
 
    void LateUpdate () {
         if(Input.GetMouseButtonDown (0)){
         Vector3 pos = Camera.main.ScreenToWorldPoint (Input.mousePosition);
         RaycastHit2D hit = Physics2D.Raycast(pos, transform.position);
         Debug.DrawLine(Vector2.zero, pos, Color.cyan);
         if (hit.collider != null) {
         gameObjectToMove = hit.collider.gameObject;    
         }
         }
 
         if(Input.GetMouseButtonDown (0) && gameObjectToMove != null){
         Vector3 mousePositions = new Vector3(gameObjectToMove.transform.position.x + Input.mousePosition.x/sensitivity,gameObjectToMove.transform.position.y + Input.mousePosition.y/sensitivity,gameObjectToMove.transform.position.z);
         gameObjectToMove.transform.position = Vector3.Lerp(gameObjectToMove.transform.position, pos, Time.smoothDeltaTime/sensitivity);
     }
 
     if(Input.GetMouseButtonUp (0) && gameObjectToMove != null)
     {
         gameObjectToMove = null;
     }
 
 }

I've just modified the logic to include that when you Raycast and there is a hit then set that game object as target gameObjectToMove. Now if mouse is down then we move that gameObjectToMove along with mouse (your code is just modified to include the same) and then when mouse button is up we set gameObjectToMove to null.

Comment
Add comment · Show 6 · 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 Ochreous · Sep 24, 2014 at 05:18 AM 0
Share

I want to make it so after I've released the mouse button the gameobject keeps moving. Any idea how I could do that? I tried giving my gameobject a rigidbody and placing rigidbody.AddForce in the if(Input.Get$$anonymous$$ouseButtonUp (0) if statement. But the gameobject isn't moving after I've let go of the mouse button.

         if(Input.Get$$anonymous$$ouseButtonUp (0) && gameObjectTo$$anonymous$$ove != null)
         {
             gameObjectTo$$anonymous$$ove.rigidbody2D.AddForce(Vector3.Lerp(gameObjectTo$$anonymous$$ove.transform.position, pos, Time.smoothDeltaTime/sensitivity));
             gameObjectTo$$anonymous$$ove = null;
         } 
avatar image HarshadK · Sep 24, 2014 at 05:30 AM 0
Share

What is happening according to current snippet of yours is that the Force is applied only one frame where the mouse button is up. And since this force isn't enough to keep game object moving it is not moving much or not moving at all.

Do you want game object to follow your mouse even after the mouse button is up? or do you want the game object to keep moving forward after the mouse button is up until user does not select another game object to move? Or you want game object to move certain distance forward after the mouse button is up?

avatar image Ochreous · Sep 24, 2014 at 08:58 PM 0
Share

I want my game object to move a certain distance(The speed that the mouse was going before I let go of the mouse button) forward after the mouse button is up. How would you find the speed that your mouse is moving?

avatar image HarshadK · Sep 25, 2014 at 05:28 AM 0
Share

Set a timer variable to zero when your mouse button is down and for all the time your mouse button is pressed down add deltaTime to it. Now when mouse button is up the value in timer is the total time for which the mouse button was down. Similarly when your mouse button is down store its position and when mouse button is up get current position of mouse and subtract it from the start position, this is your distance traveled.

Now you can easily calculate the speed using formula, speed = distance/time.

Then apply a force with Force$$anonymous$$ode.Impulse to your object based on the direction of movement of mouse (direction can be calculated using the start position and last position).

The method used to calculate the distance above will work properly in case of mouse being moved in straight line. For circular movements it may produce unrealistic results.

avatar image Ochreous · Sep 27, 2014 at 03:54 AM 0
Share

I tried putting in Forcemode.Impulse right next to my Vector3.Lerp. But I keep getting an error saying I have invalid arguments. I'm fairly certain that's how you implement Forcemode.Impulse. Do rigidbody2Ds have access to Forcemode.Impulse like 3d rigidbodies?

 gameObjectTo$$anonymous$$ove.rigidbody2D.AddForce(Vector3.Lerp(gameObjectTo$$anonymous$$ove.transform.position, pos, Time.smoothDeltaTime/sensitivity * timer),Forcemode.Impulse);



Show more comments

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

24 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

Related Questions

C# Gameobject's Script's ValuesEquals Other Gameobject's script's Values 1 Answer

Finding Distance between Angles and Points 2 Answers

adding animation dynamically by script 0 Answers

C# Adding Components From Other Gameobjects 3 Answers

Destroy + Score 1 Answer


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