天天看點

Unity實作滑鼠滑動控制物體移動一、思路:二、代碼:

一、思路:

在3D場景中,通過滑鼠點選“地面”擷取位置資訊來使玩家進行橫向相對運動。

1、在場景中建立一個Plane作為地面。

2、使用射線檢測分别記錄第一次滑鼠點選(Input.GetMouseButtonDown(0))時的位置資訊和滑鼠按下(Input.GetMouseButton(0))劃過的每個點資訊。

3、計算滑鼠滑動的偏移量,指派給玩家,使玩家獲得相應的橫向移動距離。

二、代碼:

1、定義屬性:

/// <summary>
  /// 滑鼠滑動距離
  /// </summary>
  Vector3 dis;
  
  /// <summary>
  /// 滑鼠第一次點選時的位置資訊
  /// </summary>
  private Vector3 MouseDownPos = Vector3.zero;
  
  /// <summary>
  /// 玩家位置
  /// </summary>
  Transform movingPlayer;
           

2、實作(Update):

(代碼中設定Layer層是為了避免一些錯誤點選導緻誤移動了玩家)

private void HandleInput()
  {
    //當按下滑鼠左鍵時
    if (Input.GetMouseButtonDown(0))
    {
      //從滑鼠位置發射一條射線,
      var ray = Camera.main.ScreenPointToRay(Input.mousePosition);
      //判斷當射線射到layer層為“groundLayer”時
      if (Physics.Raycast(ray, out RaycastHit hit, 100, groundLayer))
      {
        //記錄點位置資訊
        MouseDownPos = hit.point;
      }
    }
    //當按住滑鼠左鍵時
    if (Input.GetMouseButton(0))
    {
      //從滑鼠位置發射一條射線,
      var ray = Camera.main.ScreenPointToRay(Input.mousePosition);
      //判斷當射線射到layer層為“groundLayer”時
      if (Physics.Raycast(ray, out RaycastHit hit, 100, groundLayer))
      {
        //擷取滑動的距離
        dis = hit.point - MouseDownPos;
        //用playerPos來儲存玩家移動後的位置資訊
        Vector3 playerPos =  movingPlayer.position + dis;
        //這個if語句用來判斷邊界限制(如果有需要的話)。
        if (true)
        {
          //修改最終玩家移動位置
          movingPlayer.position = playerPos;
        }
        //**将滑鼠按下起始點修改為目前玩家位置
        MouseDownPos = hit.point;
      }
    }
  }
           

有更好的方法歡迎指點。

繼續閱讀