วันจันทร์ที่ 7 กุมภาพันธ์ พ.ศ. 2554

2.How to pass multiple status by one Integer?


หากต้องการส่งค่าท่าทางของตัวละครในเกมส์มากกว่า 1 ค่าไปพร้อมกันโดยใช้ตัวแปร integer เพียงตัวเดียวจะต้องทำอย่างไร
ตัวอย่างของการใช้งาน เช่น ตัวละครมีท่าทางคือ
  • กระโดด (jump)
  • ตีลังกากลับหลัง (flic-fac)
  • เตะ (kick)

ต้องการให้ตัวละคร กระโดดเตะ ต้องส่งค่าอย่างไร


2 ความคิดเห็น:

  1. ใช้หลักการคิดเช่นเดียวกับ permission ใน Unix หรือการกำหนดโหมดในการอ่านเขียน file ผ่าน api ต่างๆ คือ

    1. ใช้เลขฐาน 2 เข้ามาช่วย
    2. กำหนดค่าในแต่ละ bit ให้แทนแต่ละ status/action เช่น
    0 0 0 1 = 1 = Kick
    0 0 1 0 = 2 = Jump
    0 1 0 0 = 4 = Flic-fac
    3. ใช้หลักของ bitwise เข้ามาช่วยในการรวม status/action ต่างๆเข้าด้วยกัน เช่น action = Kick | Jump (กระโดดเตะ)
    4. ใช้หลักของ bitwise เข้ามาช่วยในการตรวจสอบ เช่น
    action & kick == kick

    ตอบลบ
  2. public class MultiState {

    private static final int kick = 1;
    private static final int jump = 2;
    private static final int flic_fac = 4;

    public static void action(int act){
    if((act & kick) == kick){
    System.out.print("kick ");
    }
    if((act & jump) == jump){
    System.out.print("jump ");
    }
    if((act & flic_fac) == flic_fac){
    System.out.print("flic-fac");
    }
    }

    public static void main(String[] args){
    int act = flic_fac | jump;
    action(act);
    }
    }

    ตอบลบ