I studied Unity3d for a short time, and the first goal was to achieve a free roaming camera.
Use the WSAD key to control the front and back movement of the camera, and use the right mouse button to control camera rotation.
This function is relatively simple, the code is also at a glance, do not do too much explanation, directly on the code.
This script can be used not only on the camera, but also on the general Gameobject.
//----------------------------------------------------------------- //1, this class as a component, included in the Gameobject. //2, left-handed coordinate system. //----------------------------------------------------------------- usingSystem.Collections; usingSystem.Collections.Generic; usingUnityengine; //----------------------------------------------------------------- Public classFicameracontrol:monobehaviour { Public floatMovespeed =30.0f; Public floatRotatespeed =0.2f; Public StaticVector3 kupdirection =NewVector3 (0.0f,1.0f,0.0f); //the member variable that controls the camera rotation. Private floatM_FLASTMOUSEPOSX =0.0f; Private floatM_flastmouseposy =0.0f; Private BOOLM_bmouserightkeydown =false; //----------------------------------------------------------------- voidStart () {}//----------------------------------------------------------------- voidUpdate () {//Judging Rotation if(Input.getmousebuttondown (1))//the right mouse button just pressed the { if(M_bmouserightkeydown = =false) {M_bmouserightkeydown=true; Vector3 Kmousepos=input.mouseposition; M_flastmouseposx=kmousepos.x; M_flastmouseposy=Kmousepos.y; } } Else if(Input.getmousebuttonup (1))//Right mouse button just lifted up the { if(M_bmouserightkeydown = =true) {M_bmouserightkeydown=false; M_flastmouseposx=0; M_flastmouseposy=0; } } Else if(Input.getmousebutton (1))//The right mouse button is in the pressed state { if(m_bmouserightkeydown) {Vector3 Kmousepos=input.mouseposition; floatFdeltax = kmousepos.x-M_flastmouseposx; floatFdeltay = Kmousepos.y-M_flastmouseposy; M_flastmouseposx=kmousepos.x; M_flastmouseposy=Kmousepos.y; Vector3 Kneweuler=Transform.eulerangles; Kneweuler.x+ = (Fdeltay *rotatespeed); Kneweuler.y+ =-(Fdeltax *rotatespeed); Transform.eulerangles=Kneweuler; } } //Judging Displacement floatFmovedeltax =0.0f; floatFmovedeltaz =0.0f; floatFdeltatime =Time.deltatime; if(Input.getkey (keycode.a)) {Fmovedeltax-= Movespeed *Fdeltatime; } if(Input.getkey (KEYCODE.D)) {Fmovedeltax+ = Movespeed *Fdeltatime; } if(Input.getkey (KEYCODE.W)) {Fmovedeltaz+ = Movespeed *Fdeltatime; } if(Input.getkey (KEYCODE.S)) {Fmovedeltaz-= Movespeed *Fdeltatime; } if(Fmovedeltax! =0.0f|| Fmovedeltaz! =0.0f) {Vector3 Kforward=Transform.forward; Vector3 Kright=Vector3.cross (kupdirection, Kforward); Vector3 Knewpos=transform.position; Knewpos+ = Kright *Fmovedeltax; Knewpos+ = Kforward *Fmovedeltaz; Transform.position=Knewpos; } } } //-----------------------------------------------------------------
[Unity3d version 5. X] To implement a free roaming camera