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
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

2D Sprite position problem

Discussion in '2D' started by Mhmud-Fadel, Feb 11, 2016.

  1. Mhmud-Fadel

    Mhmud-Fadel

    Joined:
    Nov 13, 2013
    Posts:
    41
    Hi :)
    I created 2d sprite image and my target is make it always Centered depend on screen resolution, i created the next small code but the 2d sprite disappear !! How fix it ?
    Code (JavaScript):
    1.  
    2. function Update ()
    3. {
    4. transform.position = new Vector2(Screen.width/2, Screen.height/2);
    5. }
     
  2. LiterallyJeff

    LiterallyJeff

    Joined:
    Jan 21, 2015
    Posts:
    2,802
    Well, when you do this, the position.z value is getting set to 0. That could be the reason it seems to disappear if you're not looking at the correct depth.

    Try this instead:
    Code (CSharp):
    1. function Update ()
    2. {
    3.     transform.position = new Vector3(Screen.width/2, Screen.height/2, transform.position.z);
    4. }
    Aside from that, I'm not sure why you would need to do this every single frame in Update(). If this is for some sort of UI, you're better off using a Canvas with an image anchored to the center.
     
  3. Mhmud-Fadel

    Mhmud-Fadel

    Joined:
    Nov 13, 2013
    Posts:
    41
    sorry jeffreyschoch, the problem still live !
    in the next screenshot it gone to these corrdinates:
    Capture.JPG
     
  4. LiterallyJeff

    LiterallyJeff

    Joined:
    Jan 21, 2015
    Posts:
    2,802
    I see, forgive me I should've noticed this before. In the unity game world, the units are not pixels unless your Pixels Per Unit is set to 1. By default it's 100. So by using Screen.width and Screen.height, you're getting a result in pixels.

    You'll need to divide by your pixels per unit to make that work.

    Or you'll have to convert to world like this:
    Code (CSharp):
    1. Vector3 worldPoint = Camera.main.ViewportToWorldPoint(0.5, 0.5);
    2.  
    3. transform.position = new Vector3(worldPoint.x, worldPoint.y, transform.position.z);
     
    theANMATOR2b likes this.
  5. Mhmud-Fadel

    Mhmud-Fadel

    Joined:
    Nov 13, 2013
    Posts:
    41
    worked well, Thanks ;)
     
    LiterallyJeff likes this.