Camera.main.ScreenToWorldPoint(Input.mousePosition) always returns camera position, doesnt matter where i clickUnity obtaining Vector of click eventMoving a player with GUI TextureMy shooting script does not work after respawningWhy is there no camera attached, even if I've attached it?Unity C# camera movementWandering AI in unity C#How to increment Yposition value for maincamera in unity3dHow can I push the camera upwards whenever the player fires their gun and reset the gun's position when they've stop shooting?Unity: Instantiating prefab on GameObject - Error Object is nullHow to convert keyboard controls to touch screen in Unity

ては's role in this 「追いかけては来ないでしょう」

Why doesn't a marching band have strings?

Do equal angles necessarily mean a polygon is regular?

What is the line crossing the Pacific Ocean that is shown on maps?

What reason would an alien civilization have for building a Dyson Sphere (or Swarm) if cheap Nuclear fusion is available?

Smooth Julia set for quadratic polynomials

When is the original BFGS algorithm still better than the Limited-Memory version?

Should I hide continue button until tasks are completed?

Are there any vegetarian astronauts?

In the Marvel universe, can a human have a baby with any non-human?

MH370 blackbox - is it still possible to retrieve data from it?

Why do some games show lights shine through walls?

Animation advice please

What happens when I sacrifice a creature when my Teysa Karlov is on the battlefield?

How to reply to small talk/random facts in a non-offensive way?

Analog is Obtuse!

Is it damaging to turn off a small fridge for two days every week?

How to determine what is the correct level of detail when modelling?

Through the Looking-Glass

Peace Arch without exiting USA

A player is constantly pestering me about rules, what do I do as a DM?

Unusual mail headers, evidence of an attempted attack. Have I been pwned?

Is there any set of 2-6 notes that doesn't have a chord name?

Why does the numerical solution of an ODE move away from an unstable equilibrium?



Camera.main.ScreenToWorldPoint(Input.mousePosition) always returns camera position, doesnt matter where i click


Unity obtaining Vector of click eventMoving a player with GUI TextureMy shooting script does not work after respawningWhy is there no camera attached, even if I've attached it?Unity C# camera movementWandering AI in unity C#How to increment Yposition value for maincamera in unity3dHow can I push the camera upwards whenever the player fires their gun and reset the gun's position when they've stop shooting?Unity: Instantiating prefab on GameObject - Error Object is nullHow to convert keyboard controls to touch screen in Unity






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








0















I am trying to create a script that converts mouseclick position into position in GridLayout. I trying to use Camera.main.ScreenToWorldPoint(), but its returning coordinates of camera, not of the point clicked, doesnt metter if i use static camera or camera fixed on player. I attached this script to CharacterRobotBoy prefab from standard unity assets.



using UnityEngine;

public class Position : MonoBehaviour

void Update()

if (Input.GetMouseButtonUp(0))

Vector3 pz = Camera.main.ScreenToWorldPoint(Input.mousePosition);
Debug.Log("camera:"+pz);
pz.z = 0;
GridLayout gridLayout = transform.parent.GetComponentInParent<GridLayout>();
Vector3Int cellPosition = gridLayout.WorldToCell(pz);
Debug.Log("cell position:"+cellPosition);





Can my code be fixed for the task, or is there a different solution for the problem. Thanks for your help.
PS: I am new to unity.










share|improve this question






















  • dropping everything starting the line pz.z = 0.. your code is returning my mouse location.. are you sure your camera is set main?

    – BugFinder
    Mar 25 at 10:47











  • Possible duplicate of Unity obtaining Vector of click event

    – Ruzihm
    Mar 25 at 16:36

















0















I am trying to create a script that converts mouseclick position into position in GridLayout. I trying to use Camera.main.ScreenToWorldPoint(), but its returning coordinates of camera, not of the point clicked, doesnt metter if i use static camera or camera fixed on player. I attached this script to CharacterRobotBoy prefab from standard unity assets.



using UnityEngine;

public class Position : MonoBehaviour

void Update()

if (Input.GetMouseButtonUp(0))

Vector3 pz = Camera.main.ScreenToWorldPoint(Input.mousePosition);
Debug.Log("camera:"+pz);
pz.z = 0;
GridLayout gridLayout = transform.parent.GetComponentInParent<GridLayout>();
Vector3Int cellPosition = gridLayout.WorldToCell(pz);
Debug.Log("cell position:"+cellPosition);





Can my code be fixed for the task, or is there a different solution for the problem. Thanks for your help.
PS: I am new to unity.










share|improve this question






















  • dropping everything starting the line pz.z = 0.. your code is returning my mouse location.. are you sure your camera is set main?

    – BugFinder
    Mar 25 at 10:47











  • Possible duplicate of Unity obtaining Vector of click event

    – Ruzihm
    Mar 25 at 16:36













0












0








0








I am trying to create a script that converts mouseclick position into position in GridLayout. I trying to use Camera.main.ScreenToWorldPoint(), but its returning coordinates of camera, not of the point clicked, doesnt metter if i use static camera or camera fixed on player. I attached this script to CharacterRobotBoy prefab from standard unity assets.



using UnityEngine;

public class Position : MonoBehaviour

void Update()

if (Input.GetMouseButtonUp(0))

Vector3 pz = Camera.main.ScreenToWorldPoint(Input.mousePosition);
Debug.Log("camera:"+pz);
pz.z = 0;
GridLayout gridLayout = transform.parent.GetComponentInParent<GridLayout>();
Vector3Int cellPosition = gridLayout.WorldToCell(pz);
Debug.Log("cell position:"+cellPosition);





Can my code be fixed for the task, or is there a different solution for the problem. Thanks for your help.
PS: I am new to unity.










share|improve this question














I am trying to create a script that converts mouseclick position into position in GridLayout. I trying to use Camera.main.ScreenToWorldPoint(), but its returning coordinates of camera, not of the point clicked, doesnt metter if i use static camera or camera fixed on player. I attached this script to CharacterRobotBoy prefab from standard unity assets.



using UnityEngine;

public class Position : MonoBehaviour

void Update()

if (Input.GetMouseButtonUp(0))

Vector3 pz = Camera.main.ScreenToWorldPoint(Input.mousePosition);
Debug.Log("camera:"+pz);
pz.z = 0;
GridLayout gridLayout = transform.parent.GetComponentInParent<GridLayout>();
Vector3Int cellPosition = gridLayout.WorldToCell(pz);
Debug.Log("cell position:"+cellPosition);





Can my code be fixed for the task, or is there a different solution for the problem. Thanks for your help.
PS: I am new to unity.







c# unity3d 2d






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Mar 25 at 10:28









Daniel BystricanDaniel Bystrican

691 silver badge7 bronze badges




691 silver badge7 bronze badges












  • dropping everything starting the line pz.z = 0.. your code is returning my mouse location.. are you sure your camera is set main?

    – BugFinder
    Mar 25 at 10:47











  • Possible duplicate of Unity obtaining Vector of click event

    – Ruzihm
    Mar 25 at 16:36

















  • dropping everything starting the line pz.z = 0.. your code is returning my mouse location.. are you sure your camera is set main?

    – BugFinder
    Mar 25 at 10:47











  • Possible duplicate of Unity obtaining Vector of click event

    – Ruzihm
    Mar 25 at 16:36
















dropping everything starting the line pz.z = 0.. your code is returning my mouse location.. are you sure your camera is set main?

– BugFinder
Mar 25 at 10:47





dropping everything starting the line pz.z = 0.. your code is returning my mouse location.. are you sure your camera is set main?

– BugFinder
Mar 25 at 10:47













Possible duplicate of Unity obtaining Vector of click event

– Ruzihm
Mar 25 at 16:36





Possible duplicate of Unity obtaining Vector of click event

– Ruzihm
Mar 25 at 16:36












1 Answer
1






active

oldest

votes


















2














Suppose you have a flat plane and a camera looking at it from above.
Think of the screen as the lens of the camera, and the cursor as a small ant walking over it. If I remember correctly, ScreenToWorldPoint returns the location of the ant in world-space, which is somewhere in the sky. By setting z := 0, you get a point directly below the camera, regardless of where the cursor is.



What you should do instead is cast a ray from the center of the camera-view through the ant, and collide it with the plane. The collision point is what you are looking for.
It can be done via the ScreenPointToRay method.



You should check out Brackeys RPG tutorial, he's done something similar.



Hope it helps :)






share|improve this answer



























    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "1"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55335740%2fcamera-main-screentoworldpointinput-mouseposition-always-returns-camera-positi%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    2














    Suppose you have a flat plane and a camera looking at it from above.
    Think of the screen as the lens of the camera, and the cursor as a small ant walking over it. If I remember correctly, ScreenToWorldPoint returns the location of the ant in world-space, which is somewhere in the sky. By setting z := 0, you get a point directly below the camera, regardless of where the cursor is.



    What you should do instead is cast a ray from the center of the camera-view through the ant, and collide it with the plane. The collision point is what you are looking for.
    It can be done via the ScreenPointToRay method.



    You should check out Brackeys RPG tutorial, he's done something similar.



    Hope it helps :)






    share|improve this answer





























      2














      Suppose you have a flat plane and a camera looking at it from above.
      Think of the screen as the lens of the camera, and the cursor as a small ant walking over it. If I remember correctly, ScreenToWorldPoint returns the location of the ant in world-space, which is somewhere in the sky. By setting z := 0, you get a point directly below the camera, regardless of where the cursor is.



      What you should do instead is cast a ray from the center of the camera-view through the ant, and collide it with the plane. The collision point is what you are looking for.
      It can be done via the ScreenPointToRay method.



      You should check out Brackeys RPG tutorial, he's done something similar.



      Hope it helps :)






      share|improve this answer



























        2












        2








        2







        Suppose you have a flat plane and a camera looking at it from above.
        Think of the screen as the lens of the camera, and the cursor as a small ant walking over it. If I remember correctly, ScreenToWorldPoint returns the location of the ant in world-space, which is somewhere in the sky. By setting z := 0, you get a point directly below the camera, regardless of where the cursor is.



        What you should do instead is cast a ray from the center of the camera-view through the ant, and collide it with the plane. The collision point is what you are looking for.
        It can be done via the ScreenPointToRay method.



        You should check out Brackeys RPG tutorial, he's done something similar.



        Hope it helps :)






        share|improve this answer















        Suppose you have a flat plane and a camera looking at it from above.
        Think of the screen as the lens of the camera, and the cursor as a small ant walking over it. If I remember correctly, ScreenToWorldPoint returns the location of the ant in world-space, which is somewhere in the sky. By setting z := 0, you get a point directly below the camera, regardless of where the cursor is.



        What you should do instead is cast a ray from the center of the camera-view through the ant, and collide it with the plane. The collision point is what you are looking for.
        It can be done via the ScreenPointToRay method.



        You should check out Brackeys RPG tutorial, he's done something similar.



        Hope it helps :)







        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Mar 25 at 11:14

























        answered Mar 25 at 11:03









        Null TerminatorNull Terminator

        764 bronze badges




        764 bronze badges





























            draft saved

            draft discarded
















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55335740%2fcamera-main-screentoworldpointinput-mouseposition-always-returns-camera-positi%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

            SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

            은진 송씨 목차 역사 본관 분파 인물 조선 왕실과의 인척 관계 집성촌 항렬자 인구 같이 보기 각주 둘러보기 메뉴은진 송씨세종실록 149권, 지리지 충청도 공주목 은진현