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 moliminous · Nov 24, 2015 at 03:23 PM · raycastray

GameObject follow mouse

So I'm trying to have a game object follow the mouse position but i was using out dated tutorials and guides so i had to come up with my own code. Sadly i'm kinda stuck because it tells me direction isn't part of unity vector 3? ray is the original code, but ray won't follow mouse positions, mouseworldposition works fine though.

 #pragma strict var ball:GameObject; function Start () {
 
      }
      private var hits:RaycastHit[];
      var hit:RaycastHit;
      private var ray:Ray;
      function Update () {
      var mouseWorldPosition : Vector3 = Camera.main.ScreenToWorldPoint(Input.mousePosition);
      ray=Camera.main.ScreenPointToRay(Input.mousePosition);
      
      //Debug.DrawLine(transform.position, mouseWorldPosition, Color.red);
      hits=Physics.RaycastAll(Camera.main.transform.position,ray.direction,50);
      for (var i = 0;i < hits.Length; i++){
      hit = hits;
      if(hit.collider.tag=="screen")
      {
      ball.transform.position=hit.point;
      }
      }
      }

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
0

Answer by Torigas · Nov 24, 2015 at 04:51 PM

Here's what i hacked up yesterday. This works if the Object has to move on an X-Y Plane at a certain distance to the camera.

 using UnityEngine;
 using System.Collections;
 
 public class MoveWithMouse : MonoBehaviour {
 
     // Use this for initialization
     void Start () {
     
     }
     
     // Update is called once per frame
     void Update () {
         Vector3 newPos = Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y,Mathf.Abs(Camera.main.transform.position.z-transform.position.z)));
         newPos.z = transform.position.z;
 
 
         transform.position = newPos;
     }
 }

This also sets the position. If you want a smooth follow you can do something like

 transform.position = Mathf.lerp(transform.position,newPos,0.5f);


If you want this to work on arbitrary scenes it gets slightly more complicated and you have to do an actual raycast like you tried. However this will fail if the object you move has a collider, since the system will detect a collision with the object you move and thus keep moving the object towards you:

 using UnityEngine;
 using System.Collections;
 
 public class MoveWithMousePhysical : MonoBehaviour {
 
     // Use this for initialization
     void Start () {
     
     }
 
     // Update is called once per frame
     void Update()
     {
         Ray ray = Camera.main.ScreenPointToRay(new Vector3(Input.mousePosition.x, Input.mousePosition.y, 1.0f));
         RaycastHit hit;
         if(Physics.Raycast(ray, out hit))
         {
             Vector3 newPos = hit.point;
             transform.position = newPos;
         }        
     }
 }


Now to properly stick to the first object it touches you can either work with layer masks so the raycast does not collide with the object it moves or you can take all the collisions and iterate over them:

 using UnityEngine;
 using System.Collections;
 using System.Linq;
 
 
 public class MoveWithMousePhysical : MonoBehaviour {
 
     // Use this for initialization
     void Start () {
     
     }
 
     // Update is called once per frame
     void Update()
     {
         Ray ray = Camera.main.ScreenPointToRay(new Vector3(Input.mousePosition.x, Input.mousePosition.y, 1.0f));
 
         RaycastHit[] hitpoints = Physics.RaycastAll(ray).OrderBy(h => h.distance).ToArray(); //sort by distance
         foreach (RaycastHit hit in hitpoints)
         {
             if(hit.collider.gameObject != this.gameObject)
             {
                 Vector3 newPos = hit.point;
                 transform.position = newPos;
                 break; //stop iterating
             }            
         }        
     }
 }
Comment
Add comment · Show 1 · 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 moliminous · Nov 24, 2015 at 10:18 PM 0
Share

wow, thanks for the rely, having a bit of problem incorporating your code, the sphere or ball var is a collider. I'm actually following a pretty old tutorial around the 14 $$anonymous$$ mark is where this code is giving me problems. I've been replacing code that's no longer working with functioning code YouTube video

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

5 People are following this question.

avatar image avatar image avatar image avatar image avatar image

Related Questions

How to send a Ray through a vertex? 0 Answers

Trouble with Ray & Raycasting and AddForce() 1 Answer

Why does ScreenPointToRay bug when called from IEnumerators? 1 Answer

Raycasting and foreach loops 1 Answer

How can I apply damage based on a grenade explosion, but test whether the objects are behind cover so they are not damaged even within the explosion radius? 2 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