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 /
  • Help Room /
avatar image
0
Question by viibl · Nov 11, 2011 at 05:47 PM · mouserotatelookatcursor

Rotate OBJECT to face mouse cursor for x/z based top down shooter

Normally I'd avoid reposting a repost but I've tried every single solution proffered in the other threads and they do not work. One reason, among several, is that they all use the camera to calculate the rotation angle in relation to the mouse and then rotate the camera to it. This is not desirable.

Instead, I want the primary game object to rotate to face the mouse cursor while leaving the camera in its original orientation.

Few caveats: I'm not a coder. I'm using uScript for most of my development. I'll also mention that this has kept me scratching my head for almost a week, so any prescriptive solutions that can get me over this hump are really appreciated.

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
2
Best Answer

Answer by Mox.du · Nov 12, 2011 at 05:01 AM

Hi,

I am not sure what is the problem exactly but here are two codes for rotating object toward mouse cursor around its Y axis (I believe that this is what you wanted).

Code 1: Here you have speed while rotating towards mouse. You can get rid of speed if you uncomment last line of code and comment previous.

// LookAtMouse will cause an object to rotate toward the cursor, along the y axis. // // To use, drop on an object that should always look toward the mouse cursor. // Change the speed value to alter how quickly the object rotates toward the mouse.

// speed is the rate at which the object will rotate var speed = 5;

function Update () { // Generate a plane that intersects the transform's position with an upwards normal. var playerPlane = new Plane(Vector3.up, transform.position);

 // Generate a ray from the cursor position
 var ray = Camera.main.ScreenPointToRay (Input.mousePosition);

 // Determine the point where the cursor ray intersects the plane.
 // This will be the point that the object must look towards to be looking at the mouse.
 // Raycasting to a Plane object only gives us a distance, so we'll have to take the distance,
 //   then find the point along that ray that meets that distance.  This will be the point
 //   to look at.
 var hitdist = 0.0;
 // If the ray is parallel to the plane, Raycast will return false.
 if (playerPlane.Raycast (ray, hitdist)) {
     // Get the point along the ray that hits the calculated distance.
     var targetPoint = ray.GetPoint(hitdist);

     // Determine the target rotation.  This is the rotation if the transform looks at the target point.
     var targetRotation = Quaternion.LookRotation(targetPoint - transform.position);

     // Smoothly rotate towards the target point.
   transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, speed * Time.deltaTime); // WITH SPEED
     //transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, 1); // WITHOUT SPEED!!!
 }

}

Code2: - make sure that your Camera "X" is aligned (paralel) with object "X". positive or negative.

var mouse_pos : Vector3; var target : Transform; //Assign to the object you want to rotate var object_pos : Vector3; var angle : float;

function Update () { mouse_pos = Input.mousePosition; print(mouse_pos); // mouse_pos.z = 5.23; //The distance between the camera and object object_pos = Camera.main.WorldToScreenPoint(target.position); mouse_pos.x = mouse_pos.x - object_pos.x; mouse_pos.y = mouse_pos.y - object_pos.y; angle = Mathf.Atan2(mouse_pos.y, mouse_pos.x) * Mathf.Rad2Deg; // if(angle < 90 && angle > -90){ transform.rotation = Quaternion.Euler(Vector3(0, -angle, 0)); //print(angle); //}

}

Regards.

Comment
Add comment · Show 4 · 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 viibl · Nov 12, 2011 at 08:29 PM 0
Share

The first code works, but there are some things you need to do to make it so. First, tag the camera attached to your object as $$anonymous$$ainCamera. Second, make sure that the script is attached to the gameObject, not the camera, to avoid turning the camera too. Thanks. Hoping these finer details will help folks.

avatar image Mox.du · Nov 12, 2011 at 08:48 PM 0
Share

Both codes works. Something you should always do when taking code snippets like this is to make a test with it. Open new scene, add object attach code and test, because none of these codes was written for your specific scene in sense of object na$$anonymous$$g etc. It is also good to read comments in scripts which will give you some clues.

avatar image Khyrid · Mar 16, 2014 at 03:17 PM 0
Share

I tried the first code and it works fine except that as my object rotates to face the mouse, the mouse is also being moved, so it continuously spirals around.

avatar image Lukas_Schwarz · Mar 26, 2016 at 10:56 PM 0
Share

Thanks! This helped me alot.

avatar image
0

Answer by Mox.du · Nov 13, 2011 at 12:10 AM

Hmm ...

Scripts are working with transforms only, so if your model CVs/Vertices are being altered I don't think that script is the cause by itself. Perhaps you have some children problems or bone problems or something like that. If you don't solve this you can upload small package with just the object and script, showing problem and I will take a look.

Regards.

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 Robo885 · Sep 14, 2012 at 12:10 AM

I have tried the first block of code, applying it two either my player, or the spotlight I have attached to it. My goal is to have the light face the direction of the mouse, while the camera stays put and the player can move with WASD.

However, I keep getting NullReferenceExpection. Being new, I have tried to solve this problem, but have run in to no good luck. Help would be much appreciated!

NullReferenceException UnityEngine.Camera.ScreenPointToRay (Vector3 position) Mouse_Tracking.Update () (at Assets/Mouse_Tracking.js:14)

The above implies that line 14 is the issue;

`var ray = Camera.main.ScreenPointToRay (Input.mousePosition);`

I have changed Camera to Light, but this did not help the situation. I also set it to GameObject and moved the script to the capsule itself - no fixes.

Hopefully this is enough information for a kindly stranger to help?

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

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

How to object rotate on a single axis towards another object? C# 2 Answers

Mouse Look Script Not Working 1 Answer

Script is Seemingly too slow for Mouse Cursor? 1 Answer

Rotate player with mouse. 0 Answers

"Cursor.lockState = CursorLockMode.Locked" causes Unity to run in slow motion 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