鼠标点击地面人物自动走动(也包含按键wasd&space控制) .

在漫游游戏中常用的功能就是人物在场景中行走,必要的功能就是鼠标点击地面人物就朝着那个方向行走,键盘方向键前后左右也能控制人物的行走和跳跃,在官方自带的第三人称视角中做了一点修改,官方自带的ThirdPersonController中的摄像机自动指向人物的背面,这样不能看到人物的正面或者侧面,对ThirdPersonController脚本做了修改之后,可以旋转摄像机的视角,可以摄像机跟随,类似smoothfollow的功能。

值得注意提醒的一个,就是动画系统,选择老版本的动画系统,不然会提示找不到模型,因为脚本中用的是老版本的动画系统的代码。

一、效果图



1.鼠标点击地面人物朝着点击的点前进
2.按住wasd和space键也能控制人物的动作

二、大概步骤

1.创建一个plane,设置层为Terrain,因为后面要判断是否点击的是这个层

[csharp]  view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  1. void Update () {  
  2.         MouseDownMover();  
  3.     }  
  4.   
  5.     public void MouseDownMover() {  
  6.         if(Input.GetMouseButtonDown(0)) {  //如果左击  
  7.             LayerMask layerMaskPlayers = 1 << LayerMask.NameToLayer("Terrain");  
  8.             Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);  
  9.             RaycastHit hit;  
  10.             if (Physics.Raycast(ray, out hit,600,layerMaskPlayers.value)) {  
  11.                 point = hit.point;  
  12.                 Instantiate(clickPont, point, transform.rotation);  
  13.                 TimeRealtimeSinceStartup();  
  14.             }  
  15.         }  
  16.     }  

2.准备好人物模型,并且将三个脚本拖放到人物上,并且将动画文件也拖放好,记得看前面提醒哦!

1.ThirdPersonCamera(相当于smoothflow)

[plain]  view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  1. /*  
  2. Perfect Camera Control Script  By zhoy;  
  3. Which can be toggled between First-Person Look And Third-Person Look   
  4. And it also realised freely Look-around  the world with mouse move  
  5. */  
  6.   
  7. var cameraTransform : Transform;  
  8. var distance = 7.0;  
  9.   
  10. var xSpeed = 100;  
  11. var ySpeed = 100;  
  12. var mSpeed = 10;  
  13.   
  14. var angularSmoothLag = 0.3;  
  15. var angularMaxSpeed = 15.0;  
  16.   
  17. var snapSmoothLag = 0.2;  
  18. var snapMaxSpeed = 720.0;  
  19.   
  20. var clampHeadPositionScreenSpace = 0.75;  
  21.   
  22.   
  23. private var _target : Transform;  
  24.   
  25. //var secondCamera : Camera;  
  26. private var mainCamera : Camera;  
  27.   
  28. private var controller : ThirdPersonController;  
  29.   
  30. private var headOffset    = Vector3.zero;  
  31. private var centerOffset  = Vector3.zero;  
  32.   
  33.   
  34. private var dosnap     = false;  
  35. private var snapped    = false;  
  36. private var firstPersonLook  = false;  
  37. private var angleVelocity    = 0.0;  
  38.   
  39. private var minAngleY   = -45;  
  40. private var yTopLimit   = -20.0;  
  41. private var yMinLimit   = -45;  
  42. private var yMaxLimit   =  45;  
  43. private var minDistance =  1.2;  
  44. private var maxDistance =  3.5;  
  45.   
  46.   
  47. private var current_ver_angle  = 0.0;  
  48. private var current_hor_angle  = 0.0;  
  49. private var look_height        = 0.0;  
  50.   
  51. private var bSeePicture = false;  
  52. private var curPicturePos:Vector3;  
  53. private var curPictureRotation:Quaternion;  
  54. private var curPictureTran: Transform;  
  55. function Awake ()  
  56. {  
  57.     //secondCamera.enabled = false;  
  58.     mainCamera = Camera.main;  
  59.     cameraTransform = GameObject.Find("Main Camera").transform;  
  60.     if(!cameraTransform && mainCamera)  
  61.     {  
  62.         cameraTransform = mainCamera.transform;  
  63.     }  
  64.   
  65.     if(!cameraTransform)   
  66.     {  
  67.         Debug.Log("Please assign a camera to the ThirdPersonCamera script.");  
  68.         enabled = false;      
  69.     }  
  70.                   
  71.     _target = transform;  
  72.     if (_target)  
  73.     {  
  74.         controller = _target.GetComponent(ThirdPersonController);  
  75.     }  
  76.       
  77.     if (controller)  
  78.     {  
  79.         var characterController : CharacterController = _target.collider;  
  80.         centerOffset = characterController.bounds.center - _target.position;  
  81.         headOffset = centerOffset;  
  82.           
  83.   
  84.         var look_target = _target.Find("LookTarget");  
  85.         //Debug.Log(look_target);  
  86.         var head_back_pos    = characterController.bounds.max;  
  87.         if(look_target)  
  88.         {  
  89.             head_back_pos = look_target.transform.position;  
  90.         }  
  91.         var hit_test : RaycastHit;    
  92.         var head_top = characterController.bounds.center;  
  93.         head_top.y = characterController.bounds.min.y;  
  94.           
  95.         if(Physics.Raycast(head_top,Vector3.down,hit_test,50))  
  96.         {  
  97.             look_height = head_back_pos.y - hit_test.point.y;     
  98.         }         
  99.       
  100.         //Debug.Log("look_height : " + look_height);  
  101.         headOffset.y = head_back_pos.y - _target.position.y;  
  102.   
  103.         /*下面计算、保存 相机稳定后 的初始位置与方位*/    
  104.         var hor_angle = _target.eulerAngles.y;            
  105.         var rotation_h = Quaternion.Euler (0, hor_angle, 0);      
  106.         var camera_pos = head_back_pos;  
  107.           
  108.         camera_pos += rotation_h * Vector3.back * distance; /*计算相机位置是用 头部为球中心计算的*/  
  109.           
  110.         var offsetToCenter = head_back_pos - camera_pos;  
  111.         var rotation = Quaternion.LookRotation(Vector3(offsetToCenter.x, offsetToCenter.y, offsetToCenter.z));  
  112.         current_hor_angle = 360 - rotation.eulerAngles.y;  
  113.         current_ver_angle = rotation.eulerAngles.x;   
  114.     }  
  115.     else  
  116.     {  
  117.         Debug.Log("Please assign a target to the camera that has a ThirdPersonController script attached.");  
  118.     }  
  119.   
  120.     Cut(_target, centerOffset);   
  121. }  
  122.   
  123. function SetVisible(visible)  
  124. {  
  125.     var renderers = gameObject.GetComponentsInChildren(Renderer);  
  126.     if(visible)  
  127.     {   
  128.         for(var rend:Renderer in renderers){  
  129.             rend.enabled = true;  
  130.         }  
  131.         firstPersonLook = false;  
  132.     }  
  133.     else  
  134.     {   
  135.         for(var rend:Renderer in renderers)  
  136.         {  
  137.             rend.enabled = false;  
  138.         }  
  139.         firstPersonLook = true;   
  140.     }  
  141. }  
  142. function Cut (dummyTarget : Transform, dummyCenter : Vector3)  
  143. {  
  144.     var oldSnapMaxSpeed   = snapMaxSpeed;  
  145.     var oldSnapSmooth     = snapSmoothLag;  
  146.       
  147.     snapMaxSpeed = 10000;  
  148.     snapSmoothLag = 0.001;  
  149.       
  150.     dosnap  = true;  
  151.   
  152.     Apply (transform, Vector3.zero);  
  153.       
  154.     snapMaxSpeed = oldSnapMaxSpeed;  
  155.     snapSmoothLag = oldSnapSmooth;  
  156. }  
  157.   
  158. function DebugDrawStuff ()  
  159. {  
  160.     Debug.DrawLine(_target.position, _target.position + headOffset);  
  161. }  
  162.   
  163. function AngleDistance (a : float, b : float)  
  164. {  
  165.     a = Mathf.Repeat(a, 360);  
  166.     b = Mathf.Repeat(b, 360);  
  167.       
  168.     return Mathf.Abs(b - a);  
  169. }  
  170.   
  171.   
  172. function Apply (dummyTarget : Transform, dummyCenter : Vector3)  
  173. {  
  174.        
  175.     // Early out if we don't have a target  
  176.     if (!controller)  
  177.     {  
  178.         return;  
  179.     }  
  180.     var needGoOn = false;     
  181.     var targetCenter = _target.position + centerOffset;  
  182.     var targetHead = _target.position + headOffset;  
  183.   
  184.     var strength = Input.GetAxis("Mouse ScrollWheel");  
  185.     if(strength != 0)  
  186.     {  
  187.         distance -= strength*mSpeed;  
  188.         distance =  Mathf.Clamp(distance, minDistance, maxDistance);      
  189.         /*  
  190.         if(distance <= 1)  
  191.         {  
  192.             SetVisible(false);  
  193.             minAngleY = -80;          
  194.         }     
  195.         else if(firstPersonLook)  
  196.         {  
  197.             SetVisible(true);  
  198.         }     
  199.         else if(distance < look_height)  
  200.         {  
  201.             minAngleY = (distance - 2) * (yTopLimit - yMinLimit)/(look_height - 2) - yTopLimit;   
  202.             minAngleY = - minAngleY;          
  203.         }  
  204.         else  
  205.         {  
  206.             minAngleY = yMinLimit;  
  207.         }  
  208.         */  
  209.         needGoOn = true;          
  210.     }  
  211.   
  212.     var originalTargetAngle = 360 - _target.eulerAngles.y;    
  213.     current_hor_angle = 360 - cameraTransform.eulerAngles.y;  
  214.     if(!snapped)  
  215.     {  
  216.         var targetAngle = originalTargetAngle;    
  217.         var dis_angle = 0;    
  218.         if (dosnap)  
  219.         {  
  220.             dis_angle = AngleDistance (360 - current_hor_angle, originalTargetAngle);  
  221.             current_hor_angle = Mathf.SmoothDampAngle(current_hor_angle, targetAngle, angleVelocity, snapSmoothLag, snapMaxSpeed);    
  222.         }  
  223.       
  224.             // We are close to the target, so we can stop snapping now!  
  225.         dis_angle= 0;  
  226.         if (dis_angle <= 13)  
  227.         {  
  228.             snapped = true;  
  229.             dosnap  = false;  
  230.       
  231.         }  
  232.         else if(dis_angle < 3)  
  233.         {  
  234.             dosnap  = false;          
  235.         }  
  236.         if(!snapped && !dosnap)  
  237.         {  
  238.             current_hor_angle = Mathf.SmoothDampAngle(current_hor_angle, targetAngle, angleVelocity, angularSmoothLag, angularMaxSpeed);              
  239.         }  
  240.         needGoOn = true;  
  241.     }  
  242.     else  
  243.     {  
  244.             var rotation_h =0;  
  245.             var rotation_v =0;    
  246.         if (Input.GetMouseButton(1)) {  
  247.              rotation_h =  -Input.GetAxis("Mouse X") * xSpeed *0.02;  
  248.              rotation_v =  -Input.GetAxis("Mouse Y") * ySpeed *0.02;      
  249.               
  250.         }  
  251.         needGoOn = needGoOn || (rotation_h != 0 || rotation_v != 0);  
  252.               
  253.         current_hor_angle += rotation_h;      
  254.         current_hor_angle = Mathf.Repeat(current_hor_angle, 360);         
  255.         current_ver_angle += rotation_v;  
  256.         current_ver_angle = Mathf.Clamp (current_ver_angle, minAngleY, yMaxLimit);  
  257.           
  258.     }  
  259.   
  260.     needGoOn = needGoOn || controller.IsMoving();  
  261.     needGoOn = needGoOn || controller.IsJumping();    
  262.     if(!needGoOn)/*没有鼠标键盘事件,返回即可,相机一般不会自动更新。除非未来有其他情形,那时候再添加*/  
  263.     {  
  264.         var mousecl = GetComponent("mouseMoveContr");  
  265.         var mouseMoveFlag = mousecl.getmousemoveFlag();  
  266.         if (!mouseMoveFlag) {  
  267.             return;  
  268.         }  
  269.     }  
  270.           
  271.     var rad_angle_h = (current_hor_angle - 90.0)*Mathf.Deg2Rad;  
  272.     var rad_angle_v = current_ver_angle*Mathf.Deg2Rad;  
  273.     var camera_pos = Vector3.zero;  
  274.     var radius_hor =  distance*Mathf.Cos(rad_angle_v);    
  275.     var slope      = -Mathf.Sin(rad_angle_v);     
  276.       
  277.     camera_pos.x = radius_hor*Mathf.Cos(rad_angle_h) + targetHead.x;/*计算相机位置是用 头部为球中心计算的*/  
  278.     camera_pos.z = radius_hor*Mathf.Sin(rad_angle_h) + targetHead.z;      
  279.     camera_pos.y = -distance*slope + targetHead.y;    
  280.     if(camera_pos.y < targetHead.y - look_height)  
  281.     {  
  282.         camera_pos.y = targetHead.y - look_height;  
  283.     }  
  284.       
  285.     var hit : RaycastHit;  
  286.     var modified = false;  
  287.       
  288.     var hor_dis     = 0.0;  
  289.       
  290.     if(camera_pos.y < targetCenter.y)  
  291.     {     
  292.         var testPt = camera_pos;  
  293.         testPt.y = targetCenter.y;    
  294.         if(Physics.Raycast(testPt,Vector3.down,hit,50))/*这个检测必须进行,不能完全指望后面的检测,否则会有微小的显示问题。一般发生在摄像机贴近地面跑动时*/  
  295.         {  
  296.             if(camera_pos.y < hit.point.y + 0.5)/*偏移0.5.防止过于接近地面,并且在地面上面的情况,会因为摄像机近截面问题。导致显示地下的内容*/  
  297.             {  
  298.                 modified = true;                      
  299.             }                     
  300.         }     
  301.     }  
  302.     if(modified)  
  303.     {         
  304.         hor_dis  = Vector3.Distance(targetCenter,Vector3(camera_pos.x,targetCenter.y,camera_pos.z));              
  305.         camera_pos = hit.point;  
  306.         camera_pos.y = (slope > 0.95)?hit.point.y:(camera_pos.y + hor_dis/maxDistance);  
  307.         //摄像头在脚下的时候,hor_dis几乎为0  
  308.         modified = false;  
  309.         //Debug.Log("hit down.....camera_pos : " +camera_pos);        
  310.     }     
  311.   
  312.     var real_dis = Vector3.Distance(targetCenter,camera_pos);  
  313.     var direction = camera_pos - targetCenter;  
  314.   
  315.     if(Physics.Raycast(targetCenter,direction,hit,real_dis) && hit.collider.gameObject != gameObject)  
  316.     {  
  317. //      modified = false;  
  318. //      if(hit.collider.bounds.size.magnitude <= 15) {  
  319. //          modified = false;     
  320. //      } else if (hit.collider.gameObject.tag == "bridge") {  
  321. //          camera_pos.y = camera_pos.y + 2.5;  
  322. //      } else if (hit.collider.gameObject.tag == "through"){  
  323. //          modified = false;  
  324. //      } else {  
  325. //          modified = true;  
  326. //      }  
  327. //      Debug.LogError(hit.point.y < targetHead.y);  
  328.         camera_pos = hit.point;  
  329.         if(hit.point.y < targetHead.y){  
  330.             camera_pos.y = targetHead.y;  
  331. //          Debug.LogError(camera_pos);  
  332.         }  
  333.     }  
  334. //    
  335. //  if(modified)  
  336. //  {     
  337. //      hor_dis  = Vector3.Distance(targetCenter,Vector3(camera_pos.x,targetCenter.y,camera_pos.z));              
  338. //      camera_pos   = hit.point;  
  339. //      camera_pos.y = (slope > 0.95)?hit.point.y:(camera_pos.y + hor_dis/maxDistance);/*摄像头在脚下的时候,hor_dis几乎为0*/   
  340. //  }     
  341.     cameraTransform.position = camera_pos;    
  342.     var offsetToCenter = targetHead - cameraTransform.position;  
  343.     cameraTransform.rotation = Quaternion.LookRotation(Vector3(offsetToCenter.x, offsetToCenter.y, offsetToCenter.z));  
  344.     Debug.DrawLine(targetCenter, camera_pos, Color.red);  
  345. }  
  346.   
  347. function EventMouseClicked(){  
  348. //  Debug.LogError(Input.mousePosition);  
  349.     var mousePos:Vector3 = Input.mousePosition;  
  350.     var ray:Ray;  
  351.     ray = Camera.main.ScreenPointToRay(mousePos);  
  352.     var hitInfo:RaycastHit;  
  353.     var cameraTran:Transform;  
  354.     cameraTran = Camera.main.transform;  
  355.     if(Input.GetMouseButtonDown(0)){  
  356.         if(Physics.Raycast(ray, hitInfo, 50f, (1<<9))){  
  357.             Debug.LogError(hitInfo.transform.gameObject.layer);  
  358. //          curPicturePos = hitInfo.point;  
  359. //          curPicturePos = hitInfo.transform.Find("CameraPos").position;  
  360. //          curPictureRotation = hitInfo.transform.Find("CameraPos").rotation;  
  361.             curPictureTran = hitInfo.transform.Find("CameraPos");  
  362.             bSeePicture = !bSeePicture;  
  363.             if(bSeePicture){  
  364.                 GetComponent(ThirdPersonController).enabled = false;  
  365.             }else{  
  366.                 GetComponent(ThirdPersonController).enabled = true;  
  367.             }  
  368.         }  
  369.     }  
  370. }  
  371. function LateUpdate ()   
  372. {  
  373.     if (Input.GetKeyUp (KeyCode.Tab))  
  374.     {  
  375.         var hit2 : RaycastHit;   
  376.         Debug.Log("Camera Pos.y : " + cameraTransform.position.y);  
  377.         var testPt = cameraTransform.position;  
  378.         testPt.y = 50;    
  379.         if(Physics.Raycast(testPt,Vector3.down,hit2,50))  
  380.         {  
  381.             Debug.Log("hit2.point.y : " + hit2.point.y);          
  382.         }         
  383.     }  
  384.     EventMouseClicked();  
  385.     if(!bSeePicture){  
  386.         Apply (transform, Vector3.zero);  
  387.     }else{  
  388. //      Camera.main.transform.position = transform.position;  
  389. //      Camera.main.transform.position.y = curPicturePos.y;  
  390.         Camera.main.transform.rotation = Quaternion.LookRotation(curPicturePos - Camera.main.transform.position);  
  391. //      Camera.main.transform.rotation = transform.rotation;  
  392. //      Camera.main.transform.position = curPicturePos;  
  393. //      Camera.main.transform.rotation = curPictureRotation;  
  394.         Camera.main.transform.rotation = curPictureTran.rotation;  
  395.         Camera.main.transform.position = curPictureTran.position;  
  396.     }  
  397. }  
  398.   
  399. function GetCenterOffset ()  
  400. {  
  401.     return centerOffset;  
  402. }  
  403. /*  
  404. function UpdateSecondCamPos(lookat,campos)  
  405. {  
  406.     var ccnter  = Vector3.Lerp(campos,lookat,0.5);  
  407.     var forward = ccnter - campos;  
  408.     forward = forward.normalized;  
  409.     forward.y = 0;  
  410.     var right = Vector3.Cross (Vector3.up, forward);  
  411.     var setpos = ccnter + right*30;  
  412.       
  413.     secondCamera.transform.position = setpos;  
  414.     var offset = ccnter - setpos;  
  415.     //Debug.DrawRay(campos,lookat - campos,Color.red,100000);  
  416.     var t1 = Time.time;  
  417.     GameObject.Find("TestObject").transform.position = campos;  
  418.     var t2= Time.time;  
  419.       
  420.     secondCamera.transform.rotation = Quaternion.LookRotation(Vector3(offset.x, offset.y, offset.z));     
  421. }  
  422. */  
  423. /*  
  424. if (Input.GetKeyUp (KeyCode.Tab))  
  425. {  
  426.     var hit2 : RaycastHit;   
  427.     Debug.Log("Camera Pos.y : " + cameraTransform.position.y);  
  428.     var testPt = cameraTransform.position;  
  429.     testPt.y = 50;    
  430.     if(Physics.Raycast(testPt,Vector3.down,hit2,50))  
  431.     {  
  432.         Debug.Log("hit2.point.y : " + hit2.point.y);          
  433.     }         
  434.   
  435.     if(mainCamera.enabled)  
  436.     {  
  437.         controller.SwitchCamera(secondCamera);   
  438.   
  439.     }  
  440.     else  
  441.     {  
  442.         controller.SwitchCamera(mainCamera);                      
  443.     }  
  444.   
  445. }     
  446. */  
  447.     

2.ThirdPersonController(修改版)

[plain]  view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  1. // Require a character controller to be attached to the same game object  
  2. @script RequireComponent(CharacterController)  
  3.   
  4. public var idleAnimation : AnimationClip;  
  5. public var walkAnimation : AnimationClip;  
  6. public var runAnimation : AnimationClip;  
  7. public var jumpPoseAnimation : AnimationClip;  
  8.   
  9. public var kneeAnimation : AnimationClip;  
  10.   
  11. public var walkMaxAnimationSpeed : float = 0.75;  
  12. public var trotMaxAnimationSpeed : float = 1.0;  
  13. public var runMaxAnimationSpeed : float = 1.0;  
  14. public var jumpAnimationSpeed : float = 1.15;  
  15. public var landAnimationSpeed : float = 1.0;  
  16.   
  17. private var _animation : Animation;  
  18.   
  19. enum CharacterState {  
  20.     Idle = 0,  
  21.     Walking = 1,  
  22.     Trotting = 2,  
  23.     Running = 3,  
  24.     Jumping = 4,  
  25. }  
  26.   
  27. private var _characterState : CharacterState;  
  28.   
  29. // The speed when walking  
  30. var walkSpeed = 2.0;  
  31. // after trotAfterSeconds of walking we trot with trotSpeed  
  32. var trotSpeed = 4.0;  
  33. // when pressing "Fire3" button (cmd) we start running  
  34. var runSpeed = 6.0;  
  35.   
  36. var inAirControlAcceleration = 3.0;  
  37.   
  38. // How high do we jump when pressing jump and letting go immediately  
  39. var jumpHeight = 0.5;  
  40.   
  41. // The gravity for the character  
  42. var gravity = 20.0;  
  43. // The gravity in controlled descent mode  
  44. var speedSmoothing = 10.0;  
  45. var rotateSpeed = 500.0;  
  46. var trotAfterSeconds = 3.0;  
  47.   
  48. var canJump = true;  
  49.   
  50. private var jumpRepeatTime = 0.05;  
  51. private var jumpTimeout = 0.15;  
  52. private var groundedTimeout = 0.25;  
  53.   
  54. // The camera doesnt start following the target immediately but waits for a split second to avoid too much waving around.  
  55. private var lockCameraTimer = 0.0;  
  56.   
  57. // The current move direction in x-z  
  58. private var moveDirection = Vector3.zero;  
  59. // The current vertical speed  
  60. private var verticalSpeed = 0.0;  
  61. // The current x-z move speed  
  62. private var moveSpeed = 0.0;  
  63.   
  64. // The last collision flags returned from controller.Move  
  65. private var collisionFlags : CollisionFlags;   
  66.   
  67. // Are we jumping? (Initiated with jump button and not grounded yet)  
  68. private var jumping = false;  
  69. private var jumpingReachedApex = false;  
  70.   
  71. // Are we moving backwards (This locks the camera to not do a 180 degree spin)  
  72. private var movingBack = false;  
  73. // Is the user pressing any keys?  
  74. private var isMoving = false;  
  75. // When did the user start walking (Used for going into trot after a while)  
  76. private var walkTimeStart = 0.0;  
  77. // Last time the jump button was clicked down  
  78. private var lastJumpButtonTime = -10.0;  
  79. // Last time we performed a jump  
  80. private var lastJumpTime = -1.0;  
  81.   
  82.   
  83. // the height we jumped from (Used to determine for how long to apply extra jump power after jumping.)  
  84. private var lastJumpStartHeight = 0.0;  
  85.   
  86.   
  87. private var inAirVelocity = Vector3.zero;  
  88.   
  89. private var lastGroundedTime = 0.0;  
  90.   
  91.   
  92. private var isControllable = true;  
  93.   
  94. private var activeCamera : Camera;  
  95.   
  96. //private var scenesCode = "S";  
  97.   
  98. function Start() {  
  99.     //scenesCode = GameObject.Find("Main Camera").GetComponent("createusers").getScenesCode();  
  100. }  
  101.   
  102. function LateUpdate() {  
  103.       
  104. }  
  105.   
  106. function Awake ()  
  107. {  
  108.     moveDirection = transform.TransformDirection(Vector3.forward);  
  109.       
  110.     _animation = GetComponent(Animation);  
  111.     if(!_animation)  
  112.         Debug.Log("The character you would like to control doesn't have animations. Moving her might look weird.");  
  113.       
  114.     /*  
  115. public var idleAnimation : AnimationClip;  
  116. public var walkAnimation : AnimationClip;  
  117. public var runAnimation : AnimationClip;  
  118. public var jumpPoseAnimation : AnimationClip;     
  119.     */  
  120.     if(!idleAnimation) {  
  121.         _animation = null;  
  122.         Debug.Log("No idle animation found. Turning off animations.");  
  123.     }  
  124.     if(!walkAnimation) {  
  125.         _animation = null;  
  126.         Debug.Log("No walk animation found. Turning off animations.");  
  127.     }  
  128.     if(!runAnimation) {  
  129.         _animation = null;  
  130.         Debug.Log("No run animation found. Turning off animations.");  
  131.     }  
  132.     if(!jumpPoseAnimation && canJump) {  
  133.         _animation = null;  
  134.         Debug.Log("No jump animation found and the character has canJump enabled. Turning off animations.");  
  135.     }  
  136.     activeCamera = Camera.main;  
  137.     Screen.lockCursor = false;            
  138. }  
  139. /*  
  140. function SwitchCamera(camera:Camera)  
  141. {  
  142.     activeCamera.enabled = false;  
  143.     activeCamera = camera;  
  144.     activeCamera.enabled = true;  
  145. }  
  146. */  
  147. function UpdateSmoothedMovementDirection ()  
  148. {  
  149.     var cameraTransform = activeCamera.transform;  
  150.     var grounded = IsGrounded();  
  151.       
  152.     // Forward vector relative to the camera along the x-z plane      
  153.     var forward = cameraTransform.TransformDirection(Vector3.forward);  
  154.     forward.y = 0;  
  155.     forward = forward.normalized;  
  156.   
  157.     // Right vector relative to the camera  
  158.     // Always orthogonal to the forward vector  
  159.     var right = Vector3(forward.z, 0, -forward.x);  
  160.   
  161.     var v = Input.GetAxisRaw("Vertical");  
  162.     var h = Input.GetAxisRaw("Horizontal");  
  163.   
  164.     // Are we moving backwards or looking backwards  
  165.     if (v < -0.2)  
  166.         movingBack = true;  
  167.     else  
  168.         movingBack = false;  
  169.       
  170.     var wasMoving = isMoving;  
  171.     isMoving = Mathf.Abs (h) > 0.1 || Mathf.Abs (v) > 0.1;  
  172.           
  173.     // Target direction relative to the camera  
  174.     var targetDirection = h * right + v * forward;  
  175.   
  176.     // Grounded controls  
  177.     if (grounded)  
  178.     {  
  179.         // Lock camera for short period when transitioning moving & standing still  
  180.         lockCameraTimer += Time.deltaTime;  
  181.         if (isMoving != wasMoving)  
  182.             lockCameraTimer = 0.0;  
  183.   
  184.         // We store speed and direction seperately,  
  185.         // so that when the character stands still we still have a valid forward direction  
  186.         // moveDirection is always normalized, and we only update it if there is user input.  
  187.         if (targetDirection != Vector3.zero)  
  188.         {  
  189.             // If we are really slow, just snap to the target direction  
  190.             if (moveSpeed < walkSpeed * 0.9 && grounded)  
  191.             {  
  192.                 moveDirection = targetDirection.normalized;  
  193.             }  
  194.             // Otherwise smoothly turn towards it  
  195.             else  
  196.             {  
  197.                 moveDirection = Vector3.RotateTowards(moveDirection, targetDirection, rotateSpeed * Mathf.Deg2Rad * Time.deltaTime, 1000);  
  198.                   
  199.                 moveDirection = moveDirection.normalized;  
  200.             }  
  201.         }  
  202.       
  203.         // Smooth the speed based on the current target direction  
  204.         var curSmooth = speedSmoothing * Time.deltaTime;  
  205.           
  206.         // Choose target speed  
  207.         //* We want to support analog input but make sure you cant walk faster diagonally than just forward or sideways  
  208.         var targetSpeed = Mathf.Min(targetDirection.magnitude, 1.0);  
  209.       
  210.         _characterState = CharacterState.Idle;  
  211.           
  212.         // Pick speed modifier  
  213.         if (Input.GetKey (KeyCode.LeftShift) || Input.GetKey (KeyCode.RightShift))  
  214.         {  
  215.             targetSpeed *= runSpeed;  
  216.             _characterState = CharacterState.Running;  
  217.         }  
  218.         else if (Time.time - trotAfterSeconds > walkTimeStart)  
  219.         {  
  220.             targetSpeed *= trotSpeed;  
  221.             _characterState = CharacterState.Trotting;  
  222.         }  
  223.         else  
  224.         {  
  225.             targetSpeed *= walkSpeed;  
  226.             _characterState = CharacterState.Walking;  
  227.         }  
  228.           
  229.         moveSpeed = Mathf.Lerp(moveSpeed, targetSpeed, curSmooth);  
  230.           
  231.         // Reset walk time start when we slow down  
  232.         if (moveSpeed < walkSpeed * 0.3)  
  233.             walkTimeStart = Time.time;  
  234.     }  
  235.     // In air controls  
  236.     else  
  237.   
  238.     {  
  239.         // Lock camera while in air  
  240.         if (jumping)  
  241.             lockCameraTimer = 0.0;  
  242.   
  243.         if (isMoving)  
  244.             inAirVelocity += targetDirection.normalized * Time.deltaTime * inAirControlAcceleration;  
  245.     }  
  246.           
  247. }  
  248.   
  249.   
  250. function ApplyJumping ()  
  251. {  
  252.     // Prevent jumping too fast after each other  
  253.     if (lastJumpTime + jumpRepeatTime > Time.time)  
  254.         return;  
  255.   
  256.     if (IsGrounded())   
  257.     {  
  258.         // Jump  
  259.         // - Only when pressing the button down  
  260.         // - With a timeout so you can press the button slightly before landing       
  261.         if (canJump && Time.time < lastJumpButtonTime + jumpTimeout) {  
  262.             verticalSpeed = CalculateJumpVerticalSpeed (jumpHeight);  
  263.             SendMessage("DidJump", SendMessageOptions.DontRequireReceiver);  
  264.         }  
  265.     }  
  266. }  
  267.   
  268.   
  269. function ApplyGravity ()  
  270. {  
  271.     if (isControllable) // don't move player at all if not controllable.  
  272.     {  
  273.         // Apply gravity  
  274.         var jumpButton = Input.GetButton("Jump");  
  275.           
  276.           
  277.         // When we reach the apex of the jump we send out a message  
  278.         if (jumping && !jumpingReachedApex && verticalSpeed <= 0.0)  
  279.         {  
  280.             jumpingReachedApex = true;  
  281.             SendMessage("DidJumpReachApex", SendMessageOptions.DontRequireReceiver);  
  282.         }  
  283.       
  284.         if (IsGrounded ())  
  285.             verticalSpeed = 0.0;  
  286.         else  
  287.             verticalSpeed -= gravity * Time.deltaTime;  
  288.     }  
  289. }  
  290.   
  291. function CalculateJumpVerticalSpeed (targetJumpHeight : float)  
  292. {  
  293.     // From the jump height and gravity we deduce the upwards speed   
  294.     // for the character to reach at the apex.  
  295.     return Mathf.Sqrt(2 * targetJumpHeight * gravity);  
  296. }  
  297.   
  298. function DidJump ()  
  299. {  
  300.     jumping = true;  
  301.     jumpingReachedApex = false;  
  302.     lastJumpTime = Time.time;  
  303.     lastJumpStartHeight = transform.position.y;  
  304.     lastJumpButtonTime = -10;  
  305.       
  306.     _characterState = CharacterState.Jumping;  
  307. }  
  308.   
  309. function Update() {  
  310.     if (_animation.IsPlaying("kneel")) {  
  311.         return;  
  312.     }  
  313.     if (!isControllable)  
  314.     {  
  315.         // kill all inputs if not controllable.  
  316.         Input.ResetInputAxes();  
  317.     }  
  318.   
  319.     if (Input.GetButtonDown ("Jump") && !jumping)  
  320.     {  
  321.         lastJumpButtonTime = Time.time;  
  322.     }  
  323.     if (Input.GetKeyUp (KeyCode.Escape))  
  324.     {  
  325.         Screen.lockCursor = !Screen.lockCursor;       
  326.     }  
  327.   
  328.     UpdateSmoothedMovementDirection();  
  329.       
  330.     // Apply gravity  
  331.     // - extra power jump modifies gravity  
  332.     // - controlledDescent mode modifies gravity  
  333.     ApplyGravity ();  
  334.   
  335.     // Apply jumping logic  
  336.     ApplyJumping ();  
  337.     //鼠标移动  
  338.     var mousecl = GetComponent("mouseMoveContr");  
  339.     var mouseMoveFlag = mousecl.getmousemoveFlag();  
  340.       
  341.     if (mouseMoveFlag){  
  342.         if (checkKeyDown()) {  
  343.             mousecl.setMouseMoveFlag();  
  344.         } else {  
  345.             moveDirection = mousecl.getMovement();  
  346.             moveSpeed = mousecl.getMoveSpeed();  
  347.             if (moveSpeed == 4.2) {  
  348.                 _characterState = CharacterState.Running;  
  349.             }  
  350.         }  
  351.     }  
  352.     // Calculate actual motion  
  353.     var movement = moveDirection * moveSpeed + Vector3 (0, verticalSpeed, 0) + inAirVelocity;  
  354.     movement *= Time.deltaTime;  
  355.       
  356.     // Move the controller  
  357.     var controller : CharacterController = GetComponent(CharacterController);  
  358.       
  359.     collisionFlags = controller.Move(movement);  
  360.     if (_characterState == CharacterState.Running) {  
  361.         if (mouseMoveFlag){  
  362.             if(controller.velocity.sqrMagnitude < 100) {  
  363.                 _characterState = CharacterState.Walking;  
  364.             }  
  365.         }  
  366.     }  
  367.     // ANIMATION sector  
  368.     if(_animation) {  
  369.         if(_characterState == CharacterState.Jumping)   
  370.         {  
  371.             if(!jumpingReachedApex) {  
  372.                 _animation[jumpPoseAnimation.name].speed = jumpAnimationSpeed;  
  373.                 _animation[jumpPoseAnimation.name].wrapMode = WrapMode.ClampForever;  
  374.                 _animation.CrossFade(jumpPoseAnimation.name);  
  375.             } else {  
  376.                 _animation[jumpPoseAnimation.name].speed = -landAnimationSpeed;  
  377.                 _animation[jumpPoseAnimation.name].wrapMode = WrapMode.ClampForever;  
  378.                 _animation.CrossFade(jumpPoseAnimation.name);                 
  379.             }  
  380.         }   
  381.         else   
  382.         {  
  383.           
  384.             if(controller.velocity.sqrMagnitude < 0.1) {  
  385.                 _animation.CrossFade(idleAnimation.name);  
  386.             }  
  387.             else   
  388.             {  
  389.                 if(_characterState == CharacterState.Running) {  
  390.                     _animation[runAnimation.name].speed = Mathf.Clamp(controller.velocity.magnitude, 0.0, runMaxAnimationSpeed);  
  391.                     _animation.CrossFade(runAnimation.name);      
  392.                 }  
  393.                 else if(_characterState == CharacterState.Trotting) {  
  394.                     _animation[walkAnimation.name].speed = Mathf.Clamp(controller.velocity.magnitude, 0.0, trotMaxAnimationSpeed);  
  395.                     _animation.CrossFade(walkAnimation.name);     
  396.                 }  
  397.                 else if(_characterState == CharacterState.Walking) {  
  398.                     _animation[walkAnimation.name].speed = Mathf.Clamp(controller.velocity.magnitude, 0.0, walkMaxAnimationSpeed);  
  399.                     _animation.CrossFade(walkAnimation.name);     
  400.                 }  
  401.                   
  402.             }  
  403.         }  
  404.     }  
  405.     // ANIMATION sector  
  406.       
  407.     // Set rotation to the move direction  
  408.     if (IsGrounded())  
  409.     {  
  410.           
  411.         transform.rotation = Quaternion.LookRotation(moveDirection);  
  412.   
  413.     }     
  414.     else  
  415.     {  
  416.         var xzMove = movement;  
  417.         xzMove.y = 0;  
  418.         if (xzMove.sqrMagnitude > 0.001)  
  419.         {  
  420.             transform.rotation = Quaternion.LookRotation(xzMove);  
  421.         }  
  422.     }     
  423.       
  424.     // We are in jump mode but just became grounded  
  425.     if (IsGrounded())  
  426.     {  
  427.         lastGroundedTime = Time.time;  
  428.         inAirVelocity = Vector3.zero;  
  429.         if (jumping)  
  430.         {  
  431.             jumping = false;  
  432.             SendMessage("DidLand", SendMessageOptions.DontRequireReceiver);  
  433.         }  
  434.     }  
  435. }  
  436.   
  437. function OnControllerColliderHit (hit : ControllerColliderHit )  
  438. {  
  439. //  Debug.DrawRay(hit.point, hit.normal);  
  440.     if (hit.moveDirection.y > 0.01)   
  441.         return;  
  442. }  
  443.   
  444. function GetSpeed () {  
  445.     return moveSpeed;  
  446. }  
  447.   
  448. function IsJumping () {  
  449.     return jumping;  
  450. }  
  451.   
  452. function IsGrounded () {  
  453.     return (collisionFlags & CollisionFlags.CollidedBelow) != 0;  
  454. }  
  455.   
  456. function GetDirection () {  
  457.     return moveDirection;  
  458. }  
  459.   
  460. function IsMovingBackwards () {  
  461.     return movingBack;  
  462. }  
  463.   
  464. function GetLockCameraTimer ()   
  465. {  
  466.     return lockCameraTimer;  
  467. }  
  468. function GetCharacterState() :CharacterState  
  469. {  
  470.     return _characterState;  
  471. }  
  472.   
  473. function IsMoving ()  : boolean  
  474. {  
  475.     return Mathf.Abs(Input.GetAxisRaw("Vertical")) + Mathf.Abs(Input.GetAxisRaw("Horizontal")) > 0.5;  
  476. }  
  477.   
  478. function HasJumpReachedApex ()  
  479. {  
  480.     return jumpingReachedApex;  
  481. }  
  482.   
  483. function IsGroundedWithTimeout ()  
  484. {  
  485.     return lastGroundedTime + groundedTimeout > Time.time;  
  486. }  
  487.   
  488. function Reset ()  
  489. {  
  490.     gameObject.tag = "Player";  
  491. }  
  492. function checkKeyDown():boolean {  
  493.     if (Input.GetKey(KeyCode.W)) {  
  494.         return true;  
  495.     }  
  496.     if (Input.GetKey(KeyCode.A)) {  
  497.         return true;  
  498.     }  
  499.     if (Input.GetKey(KeyCode.S)) {  
  500.         return true;  
  501.     }  
  502.     if (Input.GetKey(KeyCode.D)) {  
  503.         return true;  
  504.     }  
  505.     if (Input.GetKey(KeyCode.UpArrow)) {  
  506.         return true;  
  507.     }  
  508.     if (Input.GetKey(KeyCode.DownArrow)) {  
  509.         return true;  
  510.     }  
  511.     if (Input.GetKey(KeyCode.RightArrow)) {  
  512.         return true;  
  513.     }  
  514.     if (Input.GetKey(KeyCode.LeftArrow)) {  
  515.         return true;  
  516.     }  
  517.     return false;  
  518. }  

3.mouseMoveContr(鼠标点击人物走动)

[csharp]  view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  1. using UnityEngine;  
  2. using System.Collections;  
  3.   
  4. public class mouseMoveContr : MonoBehaviour {  
  5.     public const int PLAY_IDLE = 0;  
  6.     public const int PLAY_WALK = 1;  
  7.     public const int PLAY_RUN  = 2;  
  8.     public const int PLAY_KNEE  = 3;  
  9.     //public GameObject clickPont;  
  10.     public float walkSpeed = 2;  
  11.     public float runSpeed = 4.5f;  
  12.       
  13.     private bool moveflag = false;  
  14.       
  15.     private int gameState = 0;  
  16.     private Vector3 point;  
  17.     private float time;  
  18.     private Vector3 v;  
  19.     private Vector3 lotav;  
  20.     private float moveSpeed = 0.0f;  
  21.       
  22.     void Start () {  
  23.         SetGameState(PLAY_IDLE);  
  24.     }  
  25.       
  26.     void Update () {  
  27.         MouseDownMover();  
  28.     }  
  29.     public void MouseDownMover() {  
  30.         if(Input.GetMouseButtonDown(0)) {  
  31.             LayerMask layerMaskPlayers = 1 << LayerMask.NameToLayer("Terrain");  
  32.             Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);  
  33.             RaycastHit hit;  
  34.             if (Physics.Raycast(ray, out hit,600,layerMaskPlayers.value)) {  
  35.                 point = hit.point;  
  36.                 //Instantiate(clickPont, point, transform.rotation);  
  37.                 TimeRealtimeSinceStartup();  
  38.             }  
  39.         }  
  40.     }  
  41.     public void TimeRealtimeSinceStartup() {  
  42.         if(Time.realtimeSinceStartup - time <=0.2f) {  
  43.             SetGameState(PLAY_RUN);  
  44.         } else {  
  45.             SetGameState(PLAY_WALK);  
  46.         }  
  47.         time = Time.realtimeSinceStartup;  
  48.     }  
  49.     public void FixedUpdate() {  
  50.         switch(gameState) {  
  51.             case PLAY_IDLE:  
  52.                 break;  
  53.             case PLAY_WALK:  
  54.                 SetGameState(PLAY_WALK);  
  55.                 Move(walkSpeed);  
  56.                 break;  
  57.             case PLAY_RUN:  
  58.                 SetGameState(PLAY_RUN);  
  59.                 Move(runSpeed);  
  60.                 break;  
  61.         }  
  62.     }  
  63.     public void SetGameState(int  state) {  
  64.         switch(state) {  
  65.             case PLAY_IDLE:  
  66.                 point = transform.position;  
  67.                 //animation.Play("idle");  
  68.                 break;  
  69.             case PLAY_WALK:  
  70.                 //animation.Play("walk");  
  71.                 break;  
  72.             case PLAY_RUN:  
  73.                 //animation.Play("run");  
  74.                 break;  
  75.         }  
  76.         gameState = state;  
  77.     }  
  78.     public void Move(float speed) {  
  79.         if(Mathf.Abs(Vector3.Distance(point, transform.position))>=0.2f) {  
  80.             moveflag = true;  
  81.             CharacterController controller  = GetComponent<CharacterController>();  
  82.             v = Vector3.ClampMagnitude(point -  transform.position,speed);  
  83.             v.y = 0;  
  84.         } else {  
  85.             moveflag = false;  
  86.             SetGameState(PLAY_IDLE);  
  87.         }  
  88.         moveSpeed = speed;  
  89.     }  
  90.     public bool getmousemoveFlag() {  
  91.         return moveflag;  
  92.     }  
  93.         public void setMouseMoveFlag() {  
  94.         moveflag = false;  
  95.         point = transform.position;  
  96.     }  
  97.     public Vector3 getMovement() {  
  98.         return v;  
  99.     }  
  100.     public float getMoveSpeed() {  
  101.         return moveSpeed;  
  102.     }  
  103. }  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值