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

Question If I wanted all my calculations to be done in ScreenSpace instead of WorldSpace....

Discussion in '2D' started by Amon, Jul 2, 2021.

  1. Amon

    Amon

    Joined:
    Oct 18, 2009
    Posts:
    1,372
    How would I do that?

    Example. I want to move a 2d Square but not using the world coords. How could this be done with the result being converted to WorldSpace anyway where movement code will not be?
     
  2. Tyrant7

    Tyrant7

    Joined:
    Aug 15, 2019
    Posts:
    34
    As far as I know there is no way to override all physics or movement code in Unity, but you could use a base class which all of your objects are deriving from. And then instead of setting the position or anything like that directly, you instead call a method that does the conversion automatically from the object.
    Code (CSharp):
    1.  
    2. public abstract class ScreenObject : Monobehaviour
    3. {  
    4.       public void SetPosition(Vector3 screenPos)
    5.       {
    6.             Vector3 worldCalculations = Camera.main.ScreenToWorldPoint(screenPos)
    7.             transform.position = worldCalculations;
    8.       }
    9. }
    10.  
    And then your actual gameObject:

    Code (CSharp):
    1.  
    2. public class Player : ScreenObject
    3. {
    4.       void Update()
    5.       {
    6.             Vector3 screenCalculations;
    7.  
    8.             //Do screen calculations
    9.  
    10.             SetPosition(screenCalculations)
    11.       }
    12. }
    13.  
     
    Last edited: Jul 5, 2021