Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

Canvas Size and Positioning

Discussion in 'Scripting' started by DaRealMik, May 25, 2020.

  1. DaRealMik

    DaRealMik

    Joined:
    Jul 27, 2019
    Posts:
    69
    I tried to talk about this in another post, but haven't received a response.

    So I have 5 spawnpoints that are the position at where things randomly spawn.

    Like this:
    upload_2020-5-25_15-27-30.png
    That is one of the 5 spawnpoints on top on the canvas.

    My question is how do I make sure that the spawnpoints stay proportional to the canvas using the canvas size and position?

    Thanks.
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,971
    Anchors. Check out any good UnityEngine.UI tutorial and pay attention to how the anchors affect sizing.
     
  3. DaRealMik

    DaRealMik

    Joined:
    Jul 27, 2019
    Posts:
    69
    The problem is that the spawnpoints have a normal transform not a rect transform
     
  4. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,971
    This is a common enough question that I finally put it all together to save folks here some time:

    - convert mouse position to canvas position
    - convert canvas position to world 3D position
    - convert canvas position to 2D sprite position (in Z == 0 plane)

    Entire package enclosed... it is one directory (CanvasUIToScreen) and contains a scene setup with a 2D sprite at Z == 0, a 3D ball that rolls over a level made of primitives, and a 2D Canvas hierarchy with a marker 2D that tracks your mouse, driving through to the others.

    It happens in this order:

    - Mouse drives the 2D UI element
    - 2D UI Element drives the 2D sprite
    - 2D UI Element drives the 3D sphere

    Enjoy! Take whatever you need!
     

    Attached Files:

  5. DaRealMik

    DaRealMik

    Joined:
    Jul 27, 2019
    Posts:
    69
    I saw the package, but am confused as to how it relates to my situation.
     
  6. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,971
    Based on this statement,

    and this statement,

    You should be able to use the package I made to get back and forth from canvas to world to whatever-you-want-space, regardless of what transform is on what.

    If you cannot, then I have failed to understand what your actual needs are.
     
  7. DaRealMik

    DaRealMik

    Joined:
    Jul 27, 2019
    Posts:
    69
    I really appreciate your help and will understand your code to implement a version of it in my project. Thanks!