Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 14 Next capture
2021 2022 2023
2 captures
13 Jun 22 - 14 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 leonalchemist · Mar 25, 2015 at 02:08 AM · mousepositiontopdownaim

Top down aim at mouse

So I have this top down 3D shooter when the player aim at the mouse position but just doesnt seem very accurate, the player just never seem to truly aim towards the mouse as it is always looking at an offset, anyone knows why? :)

alt text

 var objectPos = Camera.main.WorldToScreenPoint(transform.position);
 var dir = Input.mousePosition - objectPos; 
 transform.rotation = Quaternion.Euler (Vector3(0,Mathf.Atan2 (dir.x,dir.y) * Mathf.Rad2Deg,0));


example.png (11.5 kB)
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
7
Best Answer

Answer by maccabbe · Mar 25, 2015 at 03:01 AM

The reason this is not working is inaccurate is because you are getting the rotation in terms of screen space instead of world space. Notice that the the rotation is less accurate the more you rotate your camera along the x axis.

To get the target in terms of world space first make a ray from the mouse using

 Ray ray=Camera.main.ScreenPointToRay(Input.mousePosition);

You will want a plane to intersect with the ray, in this case I'll use the ground.

 Plane plane=new Plane(Vector3.up, Vector3.zero);

Then get the target using intersect the plane and ray using a plane raycast

 float distance;
 if(plane.Raycast(ray, out distance)){
       Vector3 target = ray.GetPoint(distance);
 }

Then you can use the x and z components of the direction vector with Mathf.Atan2 like you did in your code. So your overall code will be like

 Ray ray=Camera.main.ScreenPointToRay(Input.mousePosition);
 Plane plane=new Plane(Vector3.up, Vector3.zero);
 float distance;
 if(plane.Raycast(ray, out distance)) {
     Vector3 target=ray.GetPoint(distance);
     Vector3 direction=target-transform.position;
     float rotation=Mathf.Atan2(direction.x, direction.z)*Mathf.Rad2Deg;
     transform.rotation=Quaternion.Euler(0, rotation, 0);
 }

Comment
Add comment · Show 3 · 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 leonalchemist · Mar 25, 2015 at 03:48 AM 0
Share

in the raycast, whats the "out variableName" correspond to in javascript, kinda should have mentioned that..

otherwise i have now this code; for some reason the angle is off by 90degree and still get the same problem??

 var ray : Ray = Camera.main.ScreenPointToRay(Input.mousePosition);
 var plane : Plane = new Plane(Vector3.up, Vector3.zero);
 var distance : float;
 if(plane.Raycast(ray, distance))
 {
     var target : Vector3 = ray.GetPoint(distance);
     var direction : Vector3 = target-transform.position;
     var rotation : float = $$anonymous$$athf.Atan2(direction.z, direction.x) * $$anonymous$$athf.Rad2Deg;
     transform.rotation = Quaternion.Euler(0, -rotation, 0);
 }
avatar image maccabbe · Mar 25, 2015 at 04:31 AM 0
Share

In javascript you can just ignore the out keyword, your code is correct.

I fixed the angle calculation (line 7) to fix the angle being off by 90 degrees.

Right now the plane is on the ground so your guy will look at the point your mouse intersects with the floor. It might be better to set the plane to match eye level, you'll have to make a design choice. Use the following (replace 0.5f with whatever you want eye level to be)

 Plane plane=new Plane(Vector3.up, new Vector3(0, 0.5f, 0));

avatar image leonalchemist · Mar 25, 2015 at 05:15 AM 0
Share

i think at the last line it should just be "rotation" and not "-rotation" right? otherwise seems to work like wat i had when i started which is fine... T_T cause turns out its not an ai$$anonymous$$g problem, issue was that i was using a custom cursor, like a crosshair and u need to set the cursor hotspot in the player settings to be in the center so yea... sry and thanks :)

[Edit], actually you're code seem better with games that has height and isnt viewed directly from the top, so was definitely helpful in the end :)

avatar image
2
Wiki

Answer by davient · Mar 25, 2015 at 02:56 AM

Hi there, what you need is Transform.LookAt(). And, to convert coordinates space using ScreenToWorldPoint. The below code should do ya :)

 using UnityEngine;
 using System.Collections;
 
 public class LookAtMouseScript: MonoBehaviour {
     public Camera cam;
     private GameObject gob; // we will place this object at the mouse position
     void Start () {
         gob =new GameObject();
     }
 
     void Update () {
         // position target object at mouse point 
         gob.transform.position = cam.ScreenToWorldPoint(Input.mousePosition);
         // point our object at the dummy object
         transform.LookAt(gob.transform, Vector3.forward);
     }
 
 }
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 RockingGameDeveloper · Nov 21, 2019 at 01:53 AM 0
Share

They are trying to do this in JavaScript.

avatar image
1

Answer by BarthaSzabolcs · May 04, 2021 at 01:27 PM

I know it's an old post, but this is still a valid problem.


I made a 3 minute tutorial about this with explanation and an example project.


My Solution

 using UnityEngine;
 
 namespace BarthaSzabolcs.IsometricAiming
 {
     public class IsometricAiming : MonoBehaviour
     {
         #region Datamembers
 
         #region Editor Settings
 
         [SerializeField] private LayerMask groundMask;
 
         #endregion
         #region Private Fields
 
         private Camera mainCamera;
 
         #endregion
 
         #endregion
 
 
         #region Methods
 
         #region Unity Callbacks
 
         private void Start()
         {
             // Cache the camera, Camera.main is an expensive operation.
             mainCamera = Camera.main;
         }
 
         private void Update()
         {
             Aim();
         }
 
         #endregion
 
         private void Aim()
         {
             var (success, position) = GetMousePosition();
             if (success)
             {
                 // Calculate the direction
                 var direction = position - transform.position;
 
                 // You might want to delete this line.
                 // Ignore the height difference.
                 direction.y = 0;
 
                 // Make the transform look in the direction.
                 transform.forward = direction;
             }
         }
 
         private (bool success, Vector3 position) GetMousePosition()
         {
             var ray = mainCamera.ScreenPointToRay(Input.mousePosition);
 
             if (Physics.Raycast(ray, out var hitInfo, Mathf.Infinity, groundMask))
             {
                 // The Raycast hit something, return with the position.
                 return (success: true, position: hitInfo.point);
             }
             else
             {
                 // The Raycast did not hit anything.
                 return (success: false, position: Vector3.zero);
             }
         }
 
         #endregion
     }
 }


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

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

26 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 avatar image avatar image

Related Questions

RayCasting shows wrong point 1 Answer

Rotate player to aim on one axis (Z-axis) towards mouse position/joystick - 2.5D (3D) 0 Answers

Mouse aims at object ? 1 Answer

Make my Gunpoint aim/rotate on the z axis towards my mouse cursor 1 Answer

Cast a cursor into world space from a game object? 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