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 JackBid · Apr 20, 2013 at 08:43 PM · rotationmousefacing

Problem with rotation script.

I am trying to make an object always rotate to face the mouse using a script that I found searching for a solution for this problem.

 function Update () {
 
 var mousePos = Input.mousePosition;
 mousePos.z = 10.0f; //The distance from the camera to the player object
 var lookPos :Vector3=Camera.main.ScreenToWorldPoint(mousePos);
 lookPos = lookPos - transform.position;
 var angle : float = Mathf.Atan2(lookPos.y, lookPos.x) * Mathf.Rad2Deg;
 transform.rotation = Quaternion.AngleAxis(angle, Vector3.forward);
 
 }

The problem is the mouse always seem stick to the right side of the object. Not sure how to fix this.

Comment
Add comment · Show 3
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 Howey-Do-It · Apr 20, 2013 at 09:05 PM 0
Share

What perspective is the camera looking from? Top-down, First Person, or a different perspective?

Do you want the object to instantly snap to face the mouse at all times or rotate at a certain speed towards the mouse?

avatar image JackBid · Apr 21, 2013 at 08:26 AM 0
Share

It is a 2D game where the camera is looking at the scene from the side. I want the object to instantly snap towards the mouse.

avatar image Howey-Do-It · Apr 21, 2013 at 02:15 PM 0
Share

Ok, I understand. I will send you an example of what I used in a project, when I get access to my computer at around 1:30-2:00 PST

3 Replies

· Add your reply
  • Sort: 
avatar image
0

Answer by Howey-Do-It · Apr 21, 2013 at 09:47 PM

ScreenToWorldPoint apparently always returns the center of the camera, not the mouse position. Although I could be wrong about that.

Post describing this concept further.

The best way is to use raycasting with a similar function, ScreenPointToRay.

This is a simple C# script that snaps the Transform to face the mouse, from a topdown perspective. With a little tweaking of vectors it should work perfect for you as well from the side. (You could probably use only X and Y and set Z to 0)

 using UnityEngine;
 using System.Collections;
 
 public class RotateToMouse : MonoBehaviour {
     
     public Vector3 lookPos;
     
     // Update is called once per frame
     void Update () 
     {
         
         var ray = Camera.main.ScreenPointToRay(Input.mousePosition);
         RaycastHit hit = new RaycastHit();
         if (Physics.Raycast(ray, out hit))
         {
 
             lookPos = new Vector3 (hit.point.x, 0f, hit.point.z);
             
             transform.LookAt(lookPos);
         
         }
     }
     
 }


One thing to watch out for is that you absolutely MUST have a collider that the ray will hit, otherwise you will get a null reference exception. You could just add a public LayerMask that only hits the collider's layer to the script, set up the collider in a separate layer, and then add the LayerMask variable to the Physics.Raycast(ray, out hit, HERE).

The "0f" in the look position in the "Y" spot is so that no matter how close or far away the collider is it always sets the lookPos "Y" position to absolute zero. That way the object does not look up or down in a 2D environment, which would probably look odd.

I hope that helps!

Thanks, and God bless!

Howey

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 Howey-Do-It · Apr 21, 2013 at 09:56 PM 0
Share

You can also look at this Wiki article.

LookAt$$anonymous$$ouse

whydoidoit probably knows more than I do as well... :)

avatar image
0

Answer by whydoidoit · Apr 21, 2013 at 09:52 PM

In a 2D game the best way is to use ScreenToWorldPoint having set the Z position of the 2D plane.

   var pos = (Vector3)Input.mousePosition;
   pos.z = distanceTo2DPlaneFromCamera;
   var worldPoint = Camera.main.ScreenToWorldPoint(pos);
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 robertbu · Apr 21, 2013 at 11:01 PM

The code above only works with the right setup:

  1. The camera must be looking at positive Z with no rotation on any of the axes.

  2. Line 4 is the distance in front of the camera to the 2D plane of your game. If you prefer a calculation you can use:

    var lookPos = Mathf.Abs(transform.position.z - Camera.main.transform.position.z);

  3. The script must be attached to the object that rotates, and the center of rotation of the object must match the the origin of the object.

  4. The initial rotation of the object must be (0,0,0).

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 JackBid · Apr 22, 2013 at 06:00 PM 0
Share

I didn't work

avatar image robertbu · Apr 22, 2013 at 06:09 PM 0
Share

"It didn't work" tells me nothing. Start with an new, empty scene. Put a cube in the scene anywhere it can be seen by the camera. Attach this script (the same one above with the change I suggested).

 #pragma strict
 
 function Update () {
  
     var mousePos = Input.mousePosition;
     mousePos.z = $$anonymous$$athf.Abs(transform.position.z - Camera.main.transform.position.z);
     var lookPos :Vector3=Camera.main.ScreenToWorldPoint(mousePos);
     lookPos = lookPos - transform.position;
     var angle : float = $$anonymous$$athf.Atan2(lookPos.y, lookPos.x) * $$anonymous$$athf.Rad2Deg;
     transform.rotation = Quaternion.AngleAxis(angle, Vector3.forward);
  
 }

It will work just fine. Now go to your game and compare. Recheck all the points I listed above. For example, if you are using the default plane to display your character, your rotation will not be the required (0,0,0). Something will be different between the two setups.

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

12 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

Related Questions

GameObject facing fowards 1 Answer

How to rotate an object by its pivot in script 3 Answers

click to move workig script!! but pls help with rotation!! :( 1 Answer

Getting the face direction 2 Answers

Anima 2D Bone not rotating with mouse properly 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