跳轉到內容

Celestia/Celx 指令碼/問答/使用 CELX 繫結自定義按鍵功能

來自華夏公益教科書,開放的書籍,開放的世界

使用 CELX 可以輕鬆建立自定義按鍵功能,並將它們繫結到鍵盤上的不同按鍵。以下是操作步驟:

首先,使用 CELX 建立一個 Lua 函式來實現自定義功能。在這個例子中,我們將建立一個新的按鍵功能,它會縮放活動檢視,使當前選定的物體充滿檢視。

 zoomToFit= function()
    obs = celestia:getobserver()
    obsPos = obs:getposition()
    sel = celestia:getselection()
    if sel == nil or sel:name() == "?" then return end
    selPos = sel:getposition()
    dist = obsPos:distanceto(selPos)
    rad = sel:radius()
    appDia = 2*math.atan(rad/dist)
    obs:setfov(appDia*1.20)
    celestia:flash("Zoom to fit "..sel:name(), 2) 
   end

接下來,建立一個表,將選定的按鍵對映到新函式。在這個例子中,我們將使用“z”鍵。

 keymap = {
    z = zoomToFit
 }

然後,建立一個按鍵處理函式,當按下所需的按鍵時呼叫新的 Lua 函式,並將它作為 Celestia 鍵盤迴調。

   celestia_keyboard_callback = function(key) 
       f = keymap[key]
       if f then 
          f() 
          return true
       end
          return false
   end

請注意,當輸入按鍵存在自定義按鍵定義時,回撥將返回 true,以指示 Celestia 不需要對按鍵進行進一步處理。否則,它將返回 false,Celesta 將根據內建的按鍵功能分配處理按鍵。

最後,告訴 Celestia 您希望在按下按鍵時呼叫回撥,然後等待輸入。

   celestia:requestkeyboard(true)
   repeat
       wait(10)
   until false

請注意,該指令碼有一個無限迴圈,因此您需要使用 Escape 鍵來終止它。

獲得基本指令碼後,只需定義 Lua 函式來實現它們,並將它們新增到按鍵對映中,即可輕鬆地繫結其他新的按鍵功能。

試試吧!


下載指令碼

[編輯 | 編輯原始碼]

您可以在下面找到整個指令碼(無註釋)在一個文字塊中。將灰色框中的所有內容複製並貼上到您喜歡的文字編輯器中的文字檔案中,並將該檔案儲存到您的指令碼目錄中,檔名為 zoomtofit.celx。然後在 Celestia 中開啟它(檔案/開啟指令碼)以檢視指令碼的執行效果。

-- Zoom To Fit function script
syntaxhighlight lang="text"
zoomToFit= function()
  obs = celestia:getobserver()
  obsPos = obs:getposition()
  sel = celestia:getselection()
  if sel == nil or sel:name() == "?" then return end
  selPos = sel:getposition()
  dist = obsPos:distanceto(selPos)
  rad = sel:radius()
  appDia = 2*math.atan(rad/dist)
  obs:setfov(appDia*1.20)
  celestia:flash("Zoom to fit "..sel:name(), 2) 
 end

keymap = { z = zoomToFit }

celestia_keyboard_callback = function(key) 
     f = keymap[key]
     if f then 
        f() 
        return true
     end
        return false
 end

celestia:requestkeyboard(true)
repeat
     wait(10)
until false

</syntaxhighlight>


區分大小寫

[編輯 | 編輯原始碼]

不幸的是,上面的示例沒有區分輸入的大寫字母和小寫字母。

當 Celestia 呼叫 celestia_keyboard_callback 函式時,函式的引數(在本例中為“key”)包含輸入的字母。一個簡單的 IF 語句字串可以區分它們

 celestia_keyboard_callback = function(key) 
      if key == "F" then 
         zoomToFit() 
         return true
      end
         return false
  end

這種形式的回撥函式在輸入大寫字母 F 時會呼叫 zoomToFit 函式,但會讓 Celestia 處理所有其他字母,包括小寫字母 f。


華夏公益教科書