Unity中玩家通过点击行走 或 滑动屏幕行走的实现

来源:互联网 发布:怎样推广淘宝店铺 编辑:程序博客网 时间:2024/05/01 10:53

前几天在QQ群,有人问了怎么实现人物的行走控制,正好之前做过一个游戏的小DEMO,控制一个玩家接受任务,然后去副本打怪,就有实现这功能。

分享一下相关代码吧,呵呵,自己参照Unity的demo写的不涉及其他...

[csharp] view plain copy
  1. private void TouchControl() {  
  2.         if (state != STATE_DIALOG && state != STATE_DIE) {  //如果角色不在对话状态/死亡状态,才能移动  
  3.             int touchCount = 0;  
  4.             if (touchCount < Input.touchCount) {  
  5.                 Vector2 touchPosition = Input.GetTouch(touchCount).position;  
  6.                 touchPosition.y = 480 - touchPosition.y;  
  7.   
  8.                 //如果是单击或者是滑动  
  9.                 if (Input.GetMouseButtonDown(0) || Input.GetTouch(touchCount).phase == TouchPhase.Moved ) {  
  10.                     Ray ray = mainCam.ScreenPointToRay(Input.mousePosition);  
  11.                     Debug.DrawRay(ray.origin, ray.direction * 10, Color.yellow);  // 不放心的话,画出这条射线看看  
  12.                     RaycastHit hit;  //用来从一个raycast后获取信息。  
  13.   
  14.   
  15.                     if (Physics.Raycast(ray, out hit)) {   //如果射线发生碰撞返回true  
  16.                         float touchDist = (transform.position - hit.point).magnitude; //返回向量的长度  
  17.                         if (touchDist > 0.1) {  
  18.                             targetLocation = hit.point;  
  19.                             state = STATE_MOVING;  
  20.                             targetCircle.transform.position = hit.point;  
  21.                         }  
  22.                     }  
  23.                 }  
  24.             }  
  25.         }  
  26. // 以上代码,主要是获取一个目标点,有了目标点,我们就要让玩家行走移动了。  
  27.   
  28.         else if (state == STATE_MOVING) {  
  29.             Vector3 movement = Vector3.zero;  
  30.             movement = targetLocation - transform.position;  
  31.             movement.y = 0;  
  32.             float dist = movement.magnitude;  
  33.   
  34.             if (dist < 0.1) {  
  35.                 state = STATE_STAND;  
  36.             }  
  37.             else {  
  38.                 movement = movement.normalized * speed;  
  39.             }  
  40.             movement += velocity;  
  41.             movement += Physics.gravity;  
  42.             movement *= Time.deltaTime;  
  43.   
  44.             character.Move(movement);  
  45.             FaceMovementDirection();  
  46.         }  
  47.   
  48.     //控制角色朝向移动方向  
  49.     private void  FaceMovementDirection (){   
  50.    Vector3 horizontalVelocity = character.velocity;  
  51.    horizontalVelocity.y = 0; //忽略垂直移动  
  52.    if ( horizontalVelocity.magnitude > 0.1f )  
  53.             player.forward = horizontalVelocity.normalized;  //控制玩家朝向  
  54.     } 
0 0
原创粉丝点击