Unity3d Learning camera Follow-up

Source: Internet
Author: User

Recently writing about camera following logic, in fact the first contact camera following is on Unity's official website called Roll-a-ball Tutorial, which simply involves the camera how to follow the movement of the object, the following code:

1 usingUnityengine;2 usingSystem.Collections;3 4  Public classCameracontroller:monobehaviour {5 6      PublicGameobject player;7 8     PrivateVector3 offset;9 Ten     voidStart () One     { Aoffset = transform.position-player.transform.position; -     } -      the     voidlateupdate () -     { -Transform.position = Player.transform.position +offset; -     } +}
Simple camera Move

It is easy to understand the above code: calculate the vector difference from the corresponding object at initialization, and then update the camera position in lateupdate, as to why it should be placed in lateupdate, because Lateupdate is waiting for all of the script's update to run

Updating your logic so that the camera gets the object's position is often up to date. It can be seen in Unity's reference to the scripting life cycle.

The above code, the camera is real-time tracking, in fact, the camera tracking can be changed to smooth a little, you can use unity in the MATHF.LERP, in each frame to do a linear difference, so that the camera can follow the change of a bit smoother, such as the following optimized code:

1 usingUnityengine;2 usingSystem.Collections;3 4  Public classFollowbehavior:monobehaviour {5 6      PublicTransform Trackingtarget;7      Public floatOffsetX =5.0f;8      Public floatOffsetY =4.0f;9      Public floatFollowspeed =1.0f;Ten  One      Public BOOLisxlocked =false; A      Public BOOLisylocked =false; -     //Use this for initialization -     voidStart () { the         //m_offset = transform.position-trackingtarget.position; -     } -      -     //Update is called once per frame +     voidlateupdate () { -         //transform.position = trackingtarget.position + m_offset; +         floatNEWX =transform.position.x; A         floatTargetx = trackingtarget.position.x +OffsetX; at         if(!isxlocked) -         { -Newx = Mathf.lerp (newx, Targetx, Time.deltatime *followspeed); -         } -         floatNewy =TRANSFORM.POSITION.Y; -         floatTargety = Trackingtarget.position.y +OffsetY; in         if(!isylocked) -         { toNewy = Mathf.lerp (Newy, targety, Time.deltatime *followspeed); +         } -Transform.position =NewVector3 (newx, Newy, transform.position.z); the     } *}
Smooth Tracking

The above code can satisfy most cases, but what if there are multiple focus points in a scene? For example, the business conditions to be met now are:

    • The camera needs to be moved while the mouse is dragging the screen
    • How to better switch when there are multiple focus points

Let's start with the first requirement and tell us what the conditions are:

    • Input.getmousebuttondown (0): This indicates that the left mouse button is pressed at a certain frame and will return true if you keep pressing (return FALSE) until you release and press (return true again) to refer to the document
    • Input.getmousebutton (0): This indicates that the left mouse button is currently pressed and will return true to refer to the document

Through the above interface, we can achieve drag and drop, the idea of not to elaborate, look at the code on the line:

1         voidDragcamera ()2         {3Vector3 Nowmousepos =input.mouseposition;4Vector3 move = Nowmousepos-M_origindragpos;5move = Camera.main.ScreenToViewportPoint (move) * dragspeed *-1;6             //translation No difference operation7 transform. Translate (move);8             floatx =Mathf.clamp (transform.position.x, minxandy.x, maxxandy.x);9             floaty =Mathf.clamp (TRANSFORM.POSITION.Y, MINXANDY.Y, maxxandy.y);TenVector3 pos =NewVector3 (x, y, transform.position.z); OneTransform.position =Pos; AM_origindragpos =Nowmousepos;  -         } -  the         //Update is called once per frame -         voidUpdate () -         { -             intMouse = (int) Mousetype.left; +             //The state that is pressed when a frame is recorded (after which the persistent press returns false, knowing that the next release will return TRUE if pressed) -             if(Input.getmousebuttondown (mouse)) +             { AM_bisdrag =true; at                 //Screen coordinate system -M_origindragpos =input.mouseposition; -                 return; -             } -             //represents the current release -             if(!Input.getmousebutton (mouse)) in             { -M_bisdrag =false; to                 return; +             } -         } the  *         voidlateupdate () $         {Panax Notoginseng             if(M_bisdrag) -             { the Dragcamera (); +             } A}
Drag Code

This way. In the Dragcamera function if the Origindragpos is not updated in time, the screen will always move when the mouse moves, because the calculation is produced by the move vector has always been a value, so will be constantly offset, see demand here.

The above code can be used to drag and drop the camera, but if you have a UI structure on your screen, click on the UI structure when you press the UI structure, you will actually call Input.getmousebuttondown (0), you will call the drag function, but

Often in this case, it is not necessary to set M_bisdrag to true, so how to optimize the shielding? Look at the following code:

1 //Update is called once per frame2         voidUpdate ()3         {4             intMouse = (int) Mousetype.left;5             //The state that is pressed when a frame is recorded (after which the persistent press returns false, knowing that the next release will return TRUE if pressed)6             if(Input.getmousebuttondown (mouse))7             {8                 //cannot be the UI layer9Pointereventdata Pointerdata =NewPointereventdata (eventsystem.current);TenPointerdata.position =input.mouseposition; Onelist<raycastresult> results =NewList<raycastresult>(); A EventSystem.current.RaycastAll (Pointerdata, results); -  -                 if(Results. Count >0) the                 { -                     if(results[0].gameobject.layer = = Layermask.nametolayer ("UI")) -                     { -                         return; +                     } -                 } +M_bisdrag =true; A                 //Screen coordinate system atM_origindragpos =input.mouseposition; -                 return; -             } -             //represents the current release -             if(!Input.getmousebutton (mouse)) -             { inM_bisdrag =false; -                 return; to             } +}
Masking UI

We need to mention this. The event system of the GUI in unity5.x determines the event generation to the receiving process is the input module generates event data Pointereventdata, through the projection module (Ray) to determine the specific UI, finally to the specific UI to receive data,

Since this is not the focus of this article, you can take a look at the blog post about the event system. Here we imitate the first two steps to determine whether the current mouse input point is the UI has a direct return.

Regarding the focus determination, actually is the optimization item, my side sampling is the delegate/event way to send the corresponding tranform, of course also can direct interface.

Unity3d Learning camera Follow-up

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.