do 2D games, there are no more than three modes, one is only vertical upward, one is only horizontal direction, one is horizontal and vertical direction, I recently do a game multi-level mode, different modes have not the same camera control, according to the usual wording, perhaps a lot of people wrote three camera scripts, Now I've used an enumeration type to control three different cameras, the code:
<summary>///cameractrl///created by Wang yuting//</summary>using unityengine;using System.collections;public class Cameractrl:monobehaviour {public enum cameratype{vertical,horizontal,normal}public Cameratype cameratype;public Float damptime = 1.5f;public Transform target;//camera movement speed, initial speed clear 0 private Vector3 velocity = Vect or3.zero;//camera Singleton private static Cameractrl instance;public static Cameractrl instance {get {return instance;}} The default width of the screen is 1/100 (precompiled) #if unity_androidprivate static float devheight = 8.54f;private static float devwidth = 4.8f; #elif U Nity_iphoneprivate static float devheight = 9.6f;private static float devwidth = 6.4f; #elseprivate static float Devheight = 19.20f;private static float devwidth = 10.80f; #endif//Use this for initializationvoid awake () {instance = this;//screen adaptation float screenheight = Screen.height;//debug.log ("screenheight =" + screenheight);//this. Getcomponent<camera> (). orthographicsize = Screenheight/200.0f;float Orthographicsize =This. Getcomponent<camera> (). orthographicsize;float aspectratio = screen.width * 1.0f/screen.height;float Camerawidth = orthographicsize * 2 * aspectratio;//debug.log ("camerawidth =" + camerawidth); if (Camerawidth < DevWidt h) {orthographicsize = Devwidth/(2 * aspectratio);D ebug. Log ("New orthographicsize =" + orthographicsize); Getcomponent<camera> (). Orthographicsize = Orthographicsize;}} Update is called once per framevoid Lateupdate () {if (target) {Vector3 point = getcomponent<camera> (). Worldtoviewportpoint (target.position); Vector3 delta = target.position-getcomponent<camera> (). Viewporttoworldpoint (New Vector3 (0.5f, 0.5f, point.z)); Vector3 Destination = transform.position + delta;if (cameratype = cameratype.vertical) {//Vertical camera transform.position = Vec Tor3. Smoothdamp (Transform.position, New Vector3 (transform.position.x, DESTINATION.Y, DESTINATION.Z), ref veLocity, damptime);} else if (Cameratype = = cameratype.horizontal) {//Horizontal camera transform.position = Vector3.smoothdamp (Transform.position, New Vector3 (destination.x, TRANSFORM.POSITION.Y, Destination.z), Ref velocity, damptime);} else if (Cameratype = = Cameratype.normal) {//unlimited camera transform.position = Vector3.smoothdamp (Transform.position, destination, ref velocity, damptime);}} else {settarget ();}} void Settarget () {target = Gameobject.findgameobjectwithtag ("Player"). Transform;}}
Unity 2D Game Camera control (horizontal, vertical, character centered in three modes)