banner



How To Draw A Sprite At A Screen Position Unity

Equally I mentioned in my annotate, y'all will want to position your objects relative to the view port coordinates, and then beginning this position by the extents of your renderer's bounds. In other words, move the object right to the edge of your screen, then move it completely off every bit centering it on the edge volition show it half way on screen.

          public enum StartingPlacement {     Superlative,     Lesser,     LEFT,     Right }  [RequireComponent(typeof(Renderer))] public course TestScript : MonoBehaviour {       [SerializeField] individual float startDelay = 1;     [SerializeField] private Camera mainCam = nada;                                 // chief camera     [Range(0.0f, 1.0f)] [SerializeField] private float goalPosX;                    // the % of the viewport of our X     [Range(0.0f, 1.0f)] [SerializeField] individual float goalPosY;                    // the % of the viewport of our Y     [SerializeField] private float timeToReachGoal = 2.0f;                          // the fourth dimension it takes us to accomplish goal pos from our starting position     [SerializeField] individual StartingPlacement placement = StartingPlacement.LEFT;  // which direction nosotros are starting from     [Range(0.0f, i.0f)] [SerializeField] private float offset = 0.0f;               // the other axis our start position will be % of the view port (ex: meridian is one.0f Y, but is this value Ten)     [SerializeField] private Renderer rend = naught;                                  // renderer of this object      private float zPosStart = 0f;      private void Start()     {         if (rend == null)             rend = GetComponent<Renderer>();          if (mainCam == naught)             mainCam = Camera.main;          // save our z position         zPosStart = transform.position.z;          // set our starting position based on the bounds of our photographic camera and the premises of our renderer         SetInitialPosition();          // now kickoff our motion to the goal position         StartCoroutine(MoveToGoalPostiion());     }      /// <summary>     /// Fix the initial position of our object based on the viewport position and the size of the renderer     /// </summary>     private void SetInitialPosition()     {         // with viewport coordinates, (0,0) is the lesser left and (1,1) is the tiptop right         // I am also assuming the starting position is one-half way up or across the screen - change teh 0.5 to change it          // nosotros also need to offset our current position by +/- the 10 or Y of half the premises of our renderer         switch (placement)         {             example StartingPlacement.TOP:                 transform.position = mainCam.ViewportToWorldPoint(new Vector3(offset, 1.0f, mainCam.transform.position.z));                 transform.position += new Vector3(0f, rend.bounds.extents.y, 0f);                 break;             case StartingPlacement.Bottom:                 transform.position = mainCam.ViewportToWorldPoint(new Vector3(offset, 0.0f, mainCam.transform.position.z));                 transform.position += new Vector3(0f, -rend.premises.extents.y, 0f);                 interruption;             example StartingPlacement.LEFT:                 transform.position = mainCam.ViewportToWorldPoint(new Vector3(0.0f, offset, mainCam.transform.position.z));                 transform.position += new Vector3(-rend.bounds.extents.x, 0f, 0f);                 break;             case StartingPlacement.Right:                 transform.position = mainCam.ViewportToWorldPoint(new Vector3(1.0f, offset, mainCam.transform.position.z));                 transform.position += new Vector3(rend.premises.extents.ten, 0f, 0f);                 suspension;         }          // set our start dorsum to our original Z         transform.position = new Vector3(transform.position.x, transform.position.y, zPosStart);     }      /// <summary>     /// Move from our current position to our goal position     /// </summary>     /// <returns></returns>     individual IEnumerator MoveToGoalPostiion()     {         yield return new WaitForSeconds(startDelay);         Vector2 startPos = transform.position;          float currentTime = 0.0f;          // create our goal position         Vector3 goalPos = mainCam.ViewportToWorldPoint(new Vector3(goalPosX, goalPosY, mainCam.transform.position.z));          goalPos.z = zPosStart;          while (currentTime <= timeToReachGoal)         {             transform.position = Vector2.Lerp(startPos, goalPos, currentTime / timeToReachGoal);             currentTime += Time.deltaTime;             yield return naught;         }          // set our position in case of floating betoken precision issues         transform.position = goalPos;     } }                  

Here is an example of the script working:

Example

All four sprites showtime off screen and will movement towards their goal, which is the center of the screen. I too added some functionality such as the enum specifying which management of the screen would be coming from and an offset to permit you to command the nondirectional axis starting position. Permit me know if you have questions.

Edit: Something else to add on, I am using SerializeField for all of the fields forth with the private keyword. All this means is that Unity will serialize the field, merely they tin not be accessed past other scripts. Simply assign the values you desire on the script itself, non in code.

Edit 2: I updated the code to be even simpler so less assignment is needed. Here is a gif of the script in employ showing information technology tin be uncentered. I also added naught checks so you practice not need to actually assign anything in the inspector aside from the float values. You can leave the camera and the renderer blank if you like every bit long as the script is on a renderer and the scene has a Camera.main.

Second example

Edit three: Here is a piffling more than in-depth explanation for the switch statement. To understand how I came to the solution, I will explicate how I understood your problem. You had wanted to move objects of some unknown size from the edge of the screen to a given point on the screen over time. In Unity, at that place are diverse different coordinate spaces y'all can work with, 1 of which is the viewport infinite.

I idea of using this infinite that ranges from [0.0, 1.0] (bottom left to tiptop correct) that defines the coordinates on the current photographic camera's viewport. The role ViewportToWorldPoint will catechumen a position on the viewport to a earth position. Now that I have a built-in part that can exercise all the heavy lifting, I need to fix some sort of conditional to handle how it can be used.

To me, the simplest way to describe how the movement occurs is by deciding which management (acme, bottom, left, or correct) the object volition originate from, and then give it some sort of offset relative to the direction.

For example, if an object is coming from the left direction, the offset would affect its pinnacle coming from the left direction. As I am yet using viewport, the offset will range from [0.0,1.0] being at the lowest betoken on the left to the highest.

With this information, I accept the ground for the start of the switch cases by having the enum

TOP BOTTOM LEFT Correct.

Respectively, the viewport coordinates would be

[offset, i.0] [offset 0.0] [0.0 offset] [i.0 commencement].

Now the coordinates are starting in a good position, but they are starting halfway on the screen which is not what is expected. The reason for this is considering the pivot betoken past default of sprites is the eye. To fix this, you can either change the pivot of the import image just this would lead to unexpected beliefs elsewhere, or you lot tin can account for it with another offset.

After setting the position relative to the viewport, simply have one-half of the size of the renderer and offset it depending on the management you are coming from. Pregnant if you are trying to be on the left, you need to add half of the renderer width, while on the right, you would subtract it. Combining both the viewport offset along with the offset from half the renderer will give y'all the end result of the switch statement. At the end, I am besides setting the Z component of the position every bit the viewport will make this coordinate get a flake funky.

Source: https://stackoverflow.com/questions/68071287/unity-move-png-from-outside-the-camera-to-the-game-scene-slide-in-transition

Posted by: zielinskithencerest1951.blogspot.com

0 Response to "How To Draw A Sprite At A Screen Position Unity"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel