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
10
Question by Evil_Weevil · Oct 30, 2013 at 07:35 PM · understanding logic

camera.screentoworldpoint in Perspective

It works in Orthographic. Then I turn the projection to Perspective and it stops working, though the view is 100% the same. As I understand that`s because of nature of camera.screentoworldpoint.

How do I make it work in Perspective?

(I`m using camera.screentoworldpoint to move the object with cursor).

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 Tomer-Barkan · Oct 30, 2013 at 07:37 PM 0
Share

I used it in perspective and it works just fine. Can you explain why you think it doesn't work? Give examples, and even screenshots.

avatar image Evil_Weevil · Oct 30, 2013 at 07:49 PM 0
Share

Sure.

  1. here`s the tutorial http://www.youtube.com/watch?v=-mtzOvdhsuo

  2. I have a Cube and a Camera. Cube is at origin. Camera: Orthographic, Size - 5, Far - 10.

  3. The Code:

var myCamera : Camera;

function Start () {

}

function Update () {

var vec : Vector3 = myCamera.ScreenToWorldPoint(Input.mousePosition); vec.z = 0.0; transform.position = vec;

}

So I play and everything`s fine the Cube follows the Cursor. I switch to Perspective and it stands still ((

avatar image Huacanacha · Oct 30, 2013 at 08:15 PM 0
Share

$$anonymous$$ake sure you set the z parameter to the camera near clip plane. If you just pass the raw screen coordinates (a Vector2) you will get the cameras position as Z (distance to project from camera) will be set to 0.

5 Replies

· Add your reply
  • Sort: 
avatar image
35
Best Answer

Answer by Tomer-Barkan · Oct 30, 2013 at 08:15 PM

When using a perspective camera, changing the Z position actually changes where the object appears on the screen. Think of it this way, in perspective camera, the farther the object is, the more it appears to be in the middle, even if the X and Y remain the same. The closer it gets, the more it moves to the side, until it gets close enough to pass to your left or right.

But fear not, there is a solution. You need to create a plane, on which you want to find the world position. In your case it seems you need the plane where z = 0. Then you convert the screen position to a ray, and find the place where that ray intersects with the plane:

 public Vector3 GetWorldPositionOnPlane(Vector3 screenPosition, float z) {
     Ray ray = Camera.main.ScreenPointToRay(screenPosition);
     Plane xy = new Plane(Vector3.forward, new Vector3(0, 0, z));
     float distance;
     xy.Raycast(ray, out distance);
     return ray.GetPoint(distance);
 }

 
Comment
Add comment · Show 12 · 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 Evil_Weevil · Oct 30, 2013 at 08:23 PM 0
Share

$$anonymous$$any thanks! Could you please suggest how should I adapt it for a top-down perspective?

avatar image Tomer-Barkan · Oct 30, 2013 at 08:27 PM 0
Share

It actually was intended for top down (where the objects X and Y change, but Z is always zero). I made a small mistake and fixed it (changed Vector3.up to Vector3.forward)

avatar image Evil_Weevil · Oct 30, 2013 at 08:30 PM 0
Share

cool!

sorry, should I paste it as is or after my initial code?

avatar image Tomer-Barkan · Oct 30, 2013 at 08:32 PM 0
Share

It's a method. Paste it as is, and call it ins$$anonymous$$d of calling ScreenToWorldPoint.

It's actually C# so you'll need to convert it to javascript

avatar image Evil_Weevil · Oct 30, 2013 at 08:58 PM 0
Share

in top-down in my opinion x and z change and y is 0 :))

Show more comments
avatar image
2

Answer by RodrigoAbreu · Feb 20, 2019 at 08:42 PM

Without using Raycast is still possible, however, if your camera is in perspective, you should remember that now the mousePosition conversion should also include z, as the mouse has actually no Z, it will try to use whatever values, and when you try to use ScreenToWorldPoint you'll get 0, 0, -10 ( if your camera z is on -10). With that said you should make sure that the depth is the same to convert from mousePosition to worldPoint also considering the camera's z for the conversion:

camera.ScreenToWorldPoint(new Vector3(-Input.mousePosition.x, -Input.mousePosition.y, camera.transform.position.z))

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 StarArcher · Aug 29, 2020 at 12:48 PM 0
Share

This is the answer I was looking for! Thank you :-)

avatar image
1

Answer by karma0413 · Oct 14, 2017 at 11:12 AM

I finally figured it out.... i was having a simiar problem....

Quick Description of my problem: I was using the Canvas to display a sprite ( a healthbar) which floats over all the characters. The problem however, was when i tried to obtain the WorldToScreenPoint it kept giving a result that was slightly off.... for example: the healthbar looked a little okay when the character was immediately in front of the camera... but as the character walks to the edge of the camera's fulstrum, the screens x,y placement becomes more and more incorrect.

Days and days of research and trying different combinations finally showed me that maybe there is a scaling issue which pointed me to look at Canvas / Canvas Scaler / scaling mode: scale with screen

Originally, this worked wonderfully when i had only 1 character and his healthbar stayed stuck to the top of the screen like old classic double dragon games. BUT when i made the decision to have many characters and they all need "floating healthbars", i didnt come back to re-evaluate whether this option needed to change.

Setting the canvas Scaler to: keep constant pixel size , fixes the problem and i now have the correct WORLDtoSCREENpoint that i needed! And now the healthbar floats beautifully above the characters...

BUT WAIT, ANOTHER PROBLEM! Now, if the screen resolution is small... the Ui sprite is obsurdly large..... and if the screen resolution is high definition then Ui sprite is way too small!

QUESTION: So how do i use the "scale with screen size" mode, but yet also still get back a correct WorldToScreenPoint?

ANSWER: you must take into consideration the overal scaling of the canvas when it is stretched to fit (whatever current resolution that you are using)

INSTEAD OF:

 RectTransform myRect = GetComponent<RectTransform>();
 Vector2 myPositionOnScreen = Camera.main.WorldToScreenPoint (myOwner);
 myRect.anchoredPosition = myPositionOnScreen;

YOU CALCULATE THE OVERALL SCALE FACTOR LIKE THIS:

 RectTransform myRect = GetComponent<RectTransform>();
     Vector2 myPositionOnScreen = Camera.main.WorldToScreenPoint (myOwner);
 
 Canvas copyOfMainCanvas = GameObject.Find ("Canvas").GetComponent <Canvas>();
 float scaleFactor = copyOfMainCanvas.scaleFactor
 
 Vector2 finalPosition = new Vector2 (myPositionOnScreen.x / scaleFactor , myPositionOnScreen.y / scaleFactor);
 myRect.anchoredPosition = finalPosition;


If this helped anyone please log in to give me a thumbs up....

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 Roy1337 · Oct 23, 2017 at 12:46 AM 0
Share

Hello, I am trying to use your solution in my game with orthographic cameras. When I use this solution, the health bars jitters around whenever the camera moves. At first, I thought this was a problem in the Unity editor because I thought that if I reloaded the scene, or loaded into it from my main menu, then it wouldn't jitter, but now it looks like it is always jittering. Any idea how to fix this? Thanks.

avatar image
1

Answer by Waterblade · Apr 05, 2021 at 06:29 AM

you can use 2 cameras one orthographic and other perspectve .orthographic for mouse input. Perspective for rendering

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 HuldaGnodima · Dec 04, 2021 at 05:00 PM

Whenever I google "perspective camere unity get mousepos" I always end up here, but the solutions don't work for me. I'm using a 2D-world and 2D-colliders + a perspective camera. So for anyone with a similar setup here is my solution, maybe it will work for you:

 public class PlayerInputHandler : MonoBehaviour
 {
     public Camera mainCam;
     private void Update()
     {
         if (Input.GetMouseButtonDown(0))
         {
             //Below the mouseposition will be calculated in the world-position
             var mousePos = Input.mousePosition;
             mousePos.z = -mainCam.transform.position.z; 
             Vector3 mousePosInWorld = mainCam.ScreenToWorldPoint(mousePos);
 
             //Here a check is made to see if 2D-colliders overlap some 2D-colliders
             Collider2D allColls = Physics2D.OverlapPoint(mousePosInWorld);
 
             if (allColls != null)
             {
                 Debug.Log("Hit a 2D-collider!");
             }          
         }
 
     }
 }

 



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

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

Related Questions

Please explain Quaternions! 7 Answers

sound registry 0 Answers

rigidbody.AddForce() - I just don't understand it. 1 Answer

Multitouch iPhone error! Help 1 Answer

Can somebody explain the math behind this? 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