遊戲中位運算的應用

Unity中相機的應用遮罩應用:code

camera.cullingMask = ~(1 << x);  // 渲染除去層x的全部層    
      
camera.cullingMask &= ~(1 << x); // 關閉層x    
      
camera.cullingMask |= (1 << x);  // 打開層x    
    
camera.cullingMask = 1 << x | 1 << y | 1 << z; // 攝像機只顯示第x層,y層,z層.   

 

位運算每每在遊戲用來記錄一些狀態,一個32位的整數,就能記錄32種狀態,而且只須要一個int就夠了。 在遊戲中的應用:技能狀態、等其餘狀態中。遊戲

//檢查state的第pos位是否爲1 int bitCheck(int state, int pos)
{
    return state & 1<< pos - 1;
}

//將state的第pos位的值設爲1 int bitAdd(int state, int pos)
{
    return state | (1 << (pos - 1));
}

//將state的第pos位的值設爲0 int bitDel(int state, int pos)
{
    return state & (~(1 << (pos - 1)));
}
相關文章
相關標籤/搜索