Search code examples
c#unity-game-enginezxingarcore

Instantiate based on 4 points


I'm zxing to estimate the 4 corner points of the QR Code. Following is my code to estimate the corner points.

LuminanceSource source = new RGBLuminanceSource(barcodeBitmap,QRTexture.width, QRTexture.height);
var options = new DecodingOptions { PossibleFormats = new List<BarcodeFormat> { BarcodeFormat.QR_CODE }, TryHarder = true };
this.reader = new BarcodeReader(null, null, ls => new GlobalHistogramBinarizer(ls)) { AutoRotate = false, TryInverted = false, Options = options };
Result result = this.reader.Decode(source);

This gives me a result points which has the four corners of the QR Code. How do I overlay a 3D object over the qr code based on the position of these corner points?


Solution

  • I don't know that QR reader you are using but generally you basically only need 3 points e.g.

    A-------B
    |
    |   X
    |
    C
    

    X is where you want to place your object

    So simply at

    // Assuming given values
    Vector3 A; // top-left corner
    Vector3 B; // top-right corner
    Vector3 C; // bottom-left corner
    GameObject obj;
    
    var vectorAtoB = B - A;
    var vectorAtoC = C - A;
    obj.transform.position = A + vectorAtoB * 0.5f + vectorAtoC * 0.5f;
    

    and then you also need the orientation for your object. Depending on your needs of course but the easiest way is to set the object's Transform.forward and Transform.right (it is enough to set two axis as the third one will be correct automatically)

    var vectorCtoA;
    obj.transform.forward = vectorCtoA;
    obj.transform.right = vectorAtoB;
    

    If you also need the scale then it gets tricky - or well at least you need one given value more:

    // This is the expected QR code edge length
    // if the QR code has exactly this size then the model will have scale 1,1,1
    // otherwise it is scaled according to the QR code size    
    float normalSize;
    
    var qrEdgeLength = vectorAtoB.magnitude;
    obj.transform.localScale = Vector3.one * qrEdgeLength / normalSize;