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

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

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

一、效果图



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

二、大概步骤

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

  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)

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

2.ThirdPersonController(修改版)

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

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

  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.     } 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值