halive.shootinoutside.common.util.Vector2D.java Source code

Java tutorial

Introduction

Here is the source code for halive.shootinoutside.common.util.Vector2D.java

Source

/*******************************************************************************
 * Copyright (c) HALive, 2015.
 * For Licence information see LICENSE.md
 ******************************************************************************/

package halive.shootinoutside.common.util;

import org.json.simple.JSONObject;

public class Vector2D {
    private float x;
    private float y;

    public Vector2D(float x, float y) {
        setPos(x, y);
    }

    public Vector2D(byte[] b, int offset) {
        if (offset + 8 > b.length)
            throw new ArrayIndexOutOfBoundsException("Invalid Length");
        byte[] d = new byte[8];
        int ptr = 0;
        for (int i = offset; i < offset + 8; i++) {
            d[ptr] = b[i];
            ptr++;
        }
        deserialize(d);
    }

    public static Vector2D fromJSONObject(JSONObject o) {
        float x = Float.intBitsToFloat((int) (long) o.get("x"));
        float y = Float.intBitsToFloat((int) (long) o.get("y"));
        return new Vector2D(x, y);
    }

    public float getX() {
        return x;
    }

    public void setX(float x) {
        this.x = x;
    }

    public float getY() {
        return y;
    }

    public void setY(float y) {
        this.y = y;
    }

    private void deserialize(byte[] b) {
        int iX = BitUtils.convertByteArrayToInt(b, 0);
        int iY = BitUtils.convertByteArrayToInt(b, 4);

        setPos(Float.intBitsToFloat(iX), Float.intBitsToFloat(iY));
    }

    public JSONObject toJSONObject() {
        JSONObject obj = new JSONObject();
        obj.put("x", Float.floatToIntBits(x));
        obj.put("y", Float.floatToIntBits(y));
        return obj;
    }

    public byte[] toByteArray() {
        byte[] x = BitUtils.convertIntToByteArray(Float.floatToIntBits(this.x));
        byte[] y = BitUtils.convertIntToByteArray(Float.floatToIntBits(this.y));
        return ArrayUtils.concatByteArrays(new byte[][] { x, y });
    }

    public void setPos(float x, float y) {
        this.x = x;
        this.y = y;
    }

    @Override
    public String toString() {
        return String.format("x=%f y=%f", x, y);
    }
}