Search Unity

improve drag code

Discussion in 'Scripting' started by craig4android, Dec 16, 2019.

  1. craig4android

    craig4android

    Joined:
    May 8, 2019
    Posts:
    124
    can someone improve my cam drag code
    Code (CSharp):
    1.  
    2. Plane upPlane  upPlane = new Plane(Vector3.up, 0); //camera should move parallel to this plane
    3.  
    4.     public void moveBy(Vector3 oldPointerPos, Vector3 newPointerPos)
    5.     {
    6.         Ray oldr = cam.ScreenPointToRay(newPointerPos);
    7.         Ray newr = cam.ScreenPointToRay(oldPointerPos);
    8.         float oldistance;
    9.         upPlane.Raycast(oldr, out oldistance);
    10.         float newdistance;
    11.         upPlane.Raycast(newr, out newdistance);
    12.         Vector3 oldpoint = oldr.GetPoint(oldistance);
    13.         Vector3 newpoint = newr.GetPoint(newdistance);
    14.         this.transform.position += oldpoint - newpoint;
    15.     }
    16.  
    it works but I guess it is not as fast as it could be. Can someone improve it? Pls!
     
  2. StarManta

    StarManta

    Joined:
    Oct 23, 2006
    Posts:
    8,775
    You're not doing anything in this function that strikes me as particularly slow. I suppose you could cache a few things better and avert a ray transformation but for camera drag code (which presumably only runs once a frame) but that level of optimization is only worth considering for things you do a LOT. Like hundreds or thousands of times per frame.

    What makes you think this is slow? Have you run the profiler and narrowed performance bottlenecks down to any particular scripts?
     
  3. craig4android

    craig4android

    Joined:
    May 8, 2019
    Posts:
    124
    yes you are right it's not particularly slow since it only runs once per frame, but I guess it could be faster, because all you theoretically need is an multiplier which multiplies the screen delta to convert it to the cam movement. I just don't know how to compute this multiplier. Guess you need FoV and distance from cam to plane, but maybe I'm wrong
     
    Last edited: Dec 16, 2019
  4. StarManta

    StarManta

    Joined:
    Oct 23, 2006
    Posts:
    8,775
    Don't worry about performance on stuff like this. Preoptimization will almost always cause more problems than it solves. Make your game, run the profiler, and see where the game is actually spending its time, and optimize that.

    And I'm not sure how much optimization you could actually get out of this anyway. You could cache your ScreenPointToRay result to use in the next frame and only need to call that once, but I doubt you could get rid of it altogether. (At least not without implementing an algorithm that does exactly the same math)