Test environment: Unity3d 4.6.1
1 usingUnityengine;2 usingSystem.Collections;3 4 Public classNeccc:monobehaviour5 {6 7 8 Public BOOLIsmousedown =false;9 PrivateVector3 lastmouseposition =Vector3.zero;Ten One Vector3 defaultposition; A Public floatSpeed =0.5f; - - the voidStart () - { -Lastmouseposition =input.mouseposition; - + } - //Update is called once per frame + voidUpdate () A { at - /* - * camera.screentoworldpoint screen turn to world position - from screen space to the changing position of world space. - - screen space is defined in pixels. The lower left of the screen is (0,0), the top right is (pixelwidth,pixelheight), and the z position is measured in world units to the camera distance. in */ - #regionMouse movement (Mobile phone screen movement) the mouse or the finger does not have to be on the character to follow the move note: This must be 2D game. That Select 2D when creating a game to if(Input.getmousebuttondown (0)) + { -Ismousedown =true; the * } $ if(Input.getmousebuttonup (0))Panax Notoginseng { -Ismousedown =false; theLastmouseposition =Vector3.zero; + } A if(Ismousedown) the { + if(Lastmouseposition! =Vector3.zero) - { $ //Camera.main.ScreenToWorldPoint (input.mouseposition); $Vector3 Offetset = Camera.main.ScreenToWorldPoint (input.mouseposition)-lastmouseposition; - -Transform.position = Transform.position +Offetset; the } -Lastmouseposition =transform.position;Wuyi } the #endregion - Wu } - About $ /// <summary> - ///Press the mouse button to remember the current mouse position (if it is a phone. is the location of the touch) - /// </summary> - voidOnMouseDown () A { +Defaultposition =input.mouseposition; the } - $ /// <summary> the ///Drag the mouse (drag on the phone screen) to move the object the /// </summary> the voidOnmousedrag () the { -Vector3 v = input.mouseposition-defaultposition; inTransform.position =v; the //smooth speed, as needed the //Transform.position + = v * time.deltatime * speed; AboutDefaultposition =input.mouseposition; the } the the}
Compatible PC and phone touch codes