[英]How do I access something from a virtual class so I can use them for If/Else statements in the MAIN class?
[英]how do i minimise the use of else if statements?
如何設置方向值而不必拋出其他所有選項?
if (Input.GetKey(right_button)) { direction = 1; }
else if(Input.GetKey(left_button)) { direction = -1; }
else { direction = 0; }
if (direction!=0) { rb.velocity = new Vector2(player_speed*direction, rb.velocity.y); }
我需要將玩家的輸入轉化為運動。 我無法使用軸,因為無法像使用此方法一樣容易地對其進行修改。
我如何優化這段代碼?
沒有if / else的另一種寫上面的方法是:
direction = Input.GetKey(right_button)
? 1
: Input.GetKey(left_button)
? -1
: 0;
我不知道這是否更具可讀性。 在這種情況下,我認為這比起確定的可讀性而言,更偏向於如何編寫這段代碼。 換句話說,我認為if / else語句不可讀-作為輕微的修改,我建議您將正文放在另一行而不是同一行中-但這又是個人喜好:)。
if (Input.GetKey(right_button))
{
direction = 1;
}
else if(Input.GetKey(left_button))
{
direction = -1;
}
else
{
direction = 0;
}
關於第二個問題,您的代碼中沒有任何性能問題。
另一種方法是:
// set the value of 0 to direction from the start and change it if it is needed
direction = 0;
if (Input.GetKey(right_button))
{
direction = 1;
}
if(Input.GetKey(left_button))
{
direction = -1;
}
本質上,我們從一開始就將direction
的值設置為0,並且僅在需要時才將其重新設置( Input.GetKey(right_button)
或Input.GetKey(left_button)
返回true)。
您擔心優化還為時過早。 就性能而言,@ Christos的答案是最好的(復制如下)
// set the value of 0 to direction from the start and change it if it is needed
direction = 0;
if (Input.GetKey(right_button))
{
direction = 1;
}
if(Input.GetKey(left_button))
{
direction = -1;
}
這是唯一的優化,因為它從代碼路徑中刪除了一個分支。
我會說,出於樣式和可讀性的考慮,請遠離三元運算符(使用bool?1:0語法)。 對於返回明確條件的清晰可讀值之外的所有內容,它們通常會導致代碼更加混亂。
在這些不同的實現方式中要考慮的事情是,您是否希望角色僅移動四個方向(假設您可以上下疊加)或支持對角線移動。 刪除代碼中的“ else”語句將使之成為對角線。 如果您保留“ else if”,那么您將只能沿基本方向移動。 如果您只想左右移動,則要考慮一下當兩者都按下時會發生什么。 玩家不走哪兒嗎? 玩家是否朝着最后按下的方向移動? 如果加起來,如果按下3個按鈕,如何跟蹤?
您可以定義一個集合,該集合確定哪些輸入提供哪個方向:
var directionMap = new List<(bool isInputPressed, int directionalValue)>
{
(Input.GetKey(right_button), 1),
(Input.GetKey(left_button), -1)
};
然后要獲取方向,只需從集合中isInputPressed
為true的記錄中獲取directionalValue
:
var direction = directionMap.Where(x => x.isInputPressed).Sum(x => x.directionalValue);
如果以某種方式同時按下兩個按鈕,則在此處使用.Where()
可能會產生意外的結果。 如果從未發生過這種情況,則可以將以上內容改為使用.SingleOrDefault()
:
var direction = directionMap.SingleOrDefault(x => x.isInputPressed).directionalValue;
請注意,如果一次按下多個按鈕,將產生異常。 您可以在try / catch塊中處理此異常。 或者,您可以在調用.SingleOrDefault()
之前驗證是否僅按下了一個,然后進行相應的操作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.