• 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 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 w$$anonymous$$le I hold down the left mouse button. The Raycast is $$anonymous$$tting the Gameobject because the debug.log pops up. But for some reason the Gameobject isn't following my mouse. It works fine when directly attac$$anonymous$$ng 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: " + $$anonymous$$t.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 $$anonymous$$t.collider.Gameobject instead of just $$anonymous$$t but that didn't seem to make a difference.

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




Comment

People who like this

0 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

1 Reply

· Add your reply
  • Sort: 
avatar image

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 w$$anonymous$$ch is what causing the problem.

 GameObject gameObjectToMove;
 
    void LateUpdate () {
         if(Input.GetMouseButtonDown (0)){
         Vector3 pos = Camera.main.ScreenToWorldPoint (Input.mousePosition);
         RaycastHit2D $$anonymous$$t = Physics2D.Raycast(pos, transform.position);
         Debug.DrawLine(Vector2.zero, pos, Color.cyan);
         if ($$anonymous$$t.collider != null) {
         gameObjectToMove = $$anonymous$$t.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 $$anonymous$$t 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
El Maxo
naphid

People who like this

2 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.GetMouseButtonUp (0) if statement. But the gameobject isn't moving after I've let go of the mouse button.

         if(Input.GetMouseButtonUp (0) && gameObjectToMove != null)
         {
             gameObjectToMove.rigidbody2D.AddForce(Vector3.Lerp(gameObjectToMove.transform.position, pos, Time.smoothDeltaTime/sensitivity));
             gameObjectToMove = 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 ForceMode.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?

 gameObjectToMove.rigidbody2D.AddForce(Vector3.Lerp(gameObjectToMove.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.

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

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

Getting the Furthest Point on a Ray 1 Answer

C# Function Transform to Gameobject Convert 1 Answer

C# More Accurate or Larger Raycast 1 Answer

C# GameObjectList not Setting Parent 0 Answers

C# Check If Scripted Gameobject goes Past Variable Gameobject 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