Java Code Examples for com.badlogic.gdx.utils.Array

The following are top voted examples for showing how to use com.badlogic.gdx.utils.Array. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: cocos2d-java   File: EventDispatcher.java   Source Code and License 6 votes vote down vote up
private boolean removeListenerInVector(Array<EventListener> listeners, EventListener listener) {
	if(listeners == null) {return false;}
	
	for(int i = listeners.size - 1; i >= 0; --i) {
		EventListener l = listeners.get(i);
		if(l == listener) {
			l.setRegistered(false);
			if(l.getAssociatedNode() != null) {
				dissociateNodeAndEventListener(l.getAssociatedNode(), l);
				l.setAssociatedNode(null);
			}
			if(_inDispatch <= 0) {
				listeners.removeIndex(i);
			} else {
				_toRemovedListeners.add(l);
			}
			return true;
		}
	}
	return false;
}
 
Example 2
Project: GDX-Engine   File: Game3D.java   Source Code and License 6 votes vote down vote up
/**
 * Initialze the 3D game service by instance of GameAsset and GameSetting, CameraManager, ShaderManager and LightManager
 * @param asset
 * @param baseGameSetting
 */
public void initializeGameService(IGameAsset asset,BaseGameSetting baseGameSetting, CameraManager camera, ShaderManager shader, LightManager light)
{
	batch = new SpriteBatch();
	scenes = new Array<IScene>();
	super.initializeGameService(asset, baseGameSetting);
	
	if(camera == null){
		camera = new CameraManager();
	}
	if(shader == null){
		shader = new ShaderManager();
	}
	if(light == null){
		light = new LightManager(new Vector3(0.1f, 0.1f, 0.1f));
	}
	gameService = new Game3DService(batch, asset, baseGameSetting, sceneManager, camera, shader, light);
}
 
Example 3
Project: Planet-Generator   File: SavingLoadingTests.java   Source Code and License 6 votes vote down vote up
@Test
public void testCloudJson() {
    Array<Orbiter> orbiters = new Array<>();
    Orbiter.OrbiterBlueprint orbiterBlueprint = new Orbiter.OrbiterBlueprint();
    orbiterBlueprint.angularVelocity = 70;
    int cloudObjectsCount = 10;
    for(int i = 0; i < cloudObjectsCount; i++) {
        orbiters.add(new Orbiter(new Sprite(), orbiterBlueprint));
    }

    Cloud saveCloud = new Cloud(orbiters);

    String cloudJson = json.toJson(saveCloud);
    assertNotEquals("", cloudJson);

    Cloud loadCloud = json.fromJson(Cloud.class, cloudJson);

    assertNotEquals(null, loadCloud);
    assertEquals(cloudObjectsCount, loadCloud.getCloudObjects().size);
    assertEquals(70, loadCloud.getAngularVelocity());
}
 
Example 4
Project: penguins-in-space   File: AnimationFactory.java   Source Code and License 6 votes vote down vote up
private Array<TextureRegion> createPowerupPickupAnimation(){
    Array<TextureRegion> animationSequence = new Array<>();
    for (int i = 0; i < 8; i++) {
        Texture texture;
        if (i < 2){
            texture = assetService.getTexture(PLAYER_RED);
        } else if (i < 4){
            texture = assetService.getTexture(PLAYER_GREEN);
        } else if (i < 6){
            texture = assetService.getTexture(PLAYER_BLUE);
        } else {
            texture = assetService.getTexture(PLAYER_YELLOW);
        }
        animationSequence.add(new TextureRegion(texture));
    }
    return animationSequence;
}
 
Example 5
Project: jenjin   File: Skeleton.java   Source Code and License 6 votes vote down vote up
/**
 * Updates the world transform for each bone and applies all constraints.
 * <p>
 * See <a href="http://esotericsoftware.com/spine-runtime-skeletons#World-transforms">World transforms</a> in the Spine
 * Runtimes Guide.
 */
public void updateWorldTransform() {
    // This partial update avoids computing the world transform for constrained bones when 1) the bone is not updated
    // before the constraint, 2) the constraint only needs to access the applied local transform, and 3) the constraint calls
    // updateWorldTransform.
    Array<Bone> updateCacheReset = this.updateCacheReset;
    for (int i = 0, n = updateCacheReset.size; i < n; i++) {
        Bone bone = updateCacheReset.get(i);
        bone.ax = bone.x;
        bone.ay = bone.y;
        bone.arotation = bone.rotation;
        bone.ascaleX = bone.scaleX;
        bone.ascaleY = bone.scaleY;
        bone.ashearX = bone.shearX;
        bone.ashearY = bone.shearY;
        bone.appliedValid = true;
    }
    Array<Updatable> updateCache = this.updateCache;
    for (int i = 0, n = updateCache.size; i < n; i++)
        updateCache.get(i).update();
}
 
Example 6
Project: jenjin   File: Skeleton.java   Source Code and License 6 votes vote down vote up
private void sortIkConstraint(IkConstraint constraint) {
    Bone target = constraint.target;
    sortBone(target);

    Array<Bone> constrained = constraint.bones;
    Bone parent = constrained.first();
    sortBone(parent);

    if (constrained.size > 1) {
        Bone child = constrained.peek();
        if (!updateCache.contains(child, true)) updateCacheReset.add(child);
    }

    updateCache.add(constraint);

    sortReset(parent.children);
    constrained.peek().sorted = true;
}
 
Example 7
Project: jenjin   File: Skeleton.java   Source Code and License 6 votes vote down vote up
private void sortPathConstraint(PathConstraint constraint) {
    Slot slot = constraint.target;
    int slotIndex = slot.getData().index;
    Bone slotBone = slot.bone;
    if (skin != null) sortPathConstraintAttachment(skin, slotIndex, slotBone);
    if (data.defaultSkin != null && data.defaultSkin != skin)
        sortPathConstraintAttachment(data.defaultSkin, slotIndex, slotBone);
    for (int ii = 0, nn = data.skins.size; ii < nn; ii++)
        sortPathConstraintAttachment(data.skins.get(ii), slotIndex, slotBone);

    Attachment attachment = slot.attachment;
    if (attachment instanceof PathAttachment) sortPathConstraintAttachment(attachment, slotBone);

    Array<Bone> constrained = constraint.bones;
    int boneCount = constrained.size;
    for (int ii = 0; ii < boneCount; ii++)
        sortBone(constrained.get(ii));

    updateCache.add(constraint);

    for (int ii = 0; ii < boneCount; ii++)
        sortReset(constrained.get(ii).children);
    for (int ii = 0; ii < boneCount; ii++)
        constrained.get(ii).sorted = true;
}
 
Example 8
Project: libgdx_ui_editor   File: EditorManager.java   Source Code and License 6 votes vote down vote up
public EditorManager(){
    FileChooser.setDefaultPrefsName("white-ui-editor");
    FileChooser.setSaveLastDirectory(true);

    events = new Array<>();
    assetManager = new AssetManager();
    assetManager.load("badlogic.jpg", Texture.class);
    assetManager.load("icon/select.9.png",Texture.class);
    assetManager.load("icon/align_left.png",Texture.class);
    assetManager.load("icon/align_right.png",Texture.class);
    assetManager.load("icon/align_center.png",Texture.class);
    assetManager.load("icon/align_h_center.png",Texture.class);
    assetManager.load("icon/align_bottom.png",Texture.class);
    assetManager.load("icon/align_top.png",Texture.class);
    assetManager.load("icon/label.png",Texture.class);
    assetManager.load("icon/image.png",Texture.class);
    assetManager.load("icon/group.png",Texture.class);
    assetManager.load("icon/button.png",Texture.class);
    assetManager.load("icon/checkbox.png",Texture.class);
    assetManager.load("icon/textfield.png",Texture.class);
    assetManager.finishLoading();
}
 
Example 9
Project: GangsterSquirrel   File: BossEnemy.java   Source Code and License 6 votes vote down vote up
/**
 * Sets up the enemy in the game
 * @param screen the play screen
 * @param spawnPositionX the spawn position as tile index on the x axis
 * @param spawnPositionY the spawn position as tile index on the y axis
 */
public BossEnemy(PlayScreen screen, float spawnPositionX, float spawnPositionY) {
    super(screen, spawnPositionX, spawnPositionY);

    playScreen = screen;

    // Set gameplay variables of super class for this specific type of enemy
    damageMinMax = new int[] { 10, 20 };
    health = 50;
    horizontalMoveImpulseVelocity = 0.1f;
    horizontalMaxMovementVelocity = 0.5f;

    // Animation set up
    flyFrames = new Array<>();
    for(int i = 0; i < 12; i++) {
        flyFrames.add(new TextureRegion(screen.getEnemyBossTextureAtlas().findRegion("bird"), 0, i * ENEMY_PIXEL_HEIGHT, ENEMY_PIXEL_WIDTH, ENEMY_PIXEL_HEIGHT)
        );
    }

    flyAnimation = new Animation<TextureRegion>(0.2f, flyFrames);

    currentAnimation = "bird_fly";

    stateTime = 0;
    setBounds(getX(), getY(), ENEMY_PIXEL_WIDTH / MainGameClass.PPM, ENEMY_PIXEL_HEIGHT / MainGameClass.PPM + getHeight() / 2);
}
 
Example 10
Project: cocos2d-java   File: EventManager.java   Source Code and License 6 votes vote down vote up
public boolean register(String event, Object user, OnEventCallback callback) {
	Array<StructEvent> events = eventMap.get(event);
	if(events == null) {
		events = new Array<StructEvent>();
		eventMap.put(event, events);
	}
	
	StructEvent newEvent;
	if(user == null) {
		newEvent = new StructEvent(user, callback);
	} else {
		for(StructEvent e : events) {
			if(user == e.user) {
				BaseLog.warning(TAG, "event already in map : " + event + " " + user);
				return false;
			}
		}
		newEvent = new StructEvent(user, callback);
	}
	events.add(newEvent);
	return true;
}
 
Example 11
Project: cocos2d-java   File: EventManager.java   Source Code and License 6 votes vote down vote up
/**触发事件*/
	public boolean trigger(String event, Object...args) {
		Array<StructEvent> events = eventMap.get(event);
		if(events == null) {
//			SLog.warning(TAG, "event not found : " + event);
			return false;
		}
		final int len = events.size;
		//使用副本来执行call —— 支持在执行过程中修改源数据
		StructEvent[] structEvents = new StructEvent[len];
		for(int i = 0; i < len; ++i) {
			structEvents[i] = events.get(i);
		}
		for(int i = 0; i < len; ++i) {
			structEvents[i].call(event, args);
		}
		structEvents = null;
		return true;
	}
 
Example 12
Project: Polymorph   File: PolyGame.java   Source Code and License 6 votes vote down vote up
private void initEntities(TextureAtlas textureAtlas) {
    final float mobWidth = Polymorph.WORLD_WIDTH/4;
    player = new Player(new Vector2(Polymorph.WORLD_WIDTH/2 - mobWidth/2, Polymorph.WORLD_HEIGHT/3-mobWidth),
                        new Dimension(mobWidth, mobWidth));

    slots = new Array<Slot>();
    slotPool = new Pool<Slot>() {
        @Override
        protected Slot newObject() {
            return new Slot(new Vector2(SLOT_SPAWN_POINT),
                            new Vector2(slotVelocity),
                            new Dimension(mobWidth, mobWidth));
        }
    };

    Dimension mapSize = new Dimension(Polymorph.WORLD_WIDTH, (int)(Polymorph.WORLD_HEIGHT*1.1f));
    TextureRegion mapTexture = textureAtlas.findRegion("background");
    Map mapFront = new Map(new Vector2(0, 0), mapVelocity, mapSize, mapTexture);
    Map mapBack = new Map(new Vector2(0, -mapSize.height + 5), mapVelocity, mapSize, mapTexture);
    maps = new Map[]{mapFront, mapBack};
}
 
Example 13
Project: cocos2d-java   File: SpriteFrameCache.java   Source Code and License 6 votes vote down vote up
/**
 * 读取gdx textureAtlas文件
 * @param filePath atlas 文件路径 也可以自定义
 * @param atlas
 */
public void addSpriteFrameWithTextureAtlas(String filePath, TextureAtlas atlas) {
	if(_atlases.containsKey(filePath)) {
		CCLog.debug(this.getClass(), "file loaded : " + filePath);
		return;
	}
	
	_atlases.put(filePath, atlas);
	
	Array<AtlasRegion> rs = atlas.getRegions();
	for(AtlasRegion r : rs) {
		TextureRegion ret = _spriteFrames.put(r.name, r);
		if(ret != null) {
			CCLog.debug(this.getClass(), "region name exists : " + r.name);
		}
	}
}
 
Example 14
Project: gdx-gamesvcs   File: GpgsClient.java   Source Code and License 6 votes vote down vote up
@Override
public boolean fetchGameStates(final IFetchGameStatesListResponseListener callback) {
    if (!driveApiEnabled)
        throw new UnsupportedOperationException("To use game states, enable Drive API when initializing");

    if (connected) {
        background(new SafeRunnable() {
            @Override
            public void run() throws IOException {
                Array<String> result = null;
                try {
                    result = fetchGameStatesSync();
                } finally {
                    callback.onFetchGameStatesListResponse(result);
                }
            }
        });
    }
    return connected;
}
 
Example 15
Project: gdx-gamesvcs   File: GpgsClient.java   Source Code and License 6 votes vote down vote up
@Override
public boolean fetchLeaderboardEntries(final String leaderBoardId, final int limit, final boolean
        relatedToPlayer, final IFetchLeaderBoardEntriesResponseListener callback) {
    if (connected) {
        background(new SafeRunnable() {
            @Override
            public void run() throws IOException {
                Array<ILeaderBoardEntry> result = null;
                try {
                    result = fetchLeaderboardSync(leaderBoardId, limit, relatedToPlayer, false);
                } finally {
                    callback.onLeaderBoardResponse(result);
                }
            }
        });
    }
    return connected;
}
 
Example 16
Project: SpaceChaos   File: AtlasAnimationComponent.java   Source Code and License 6 votes vote down vote up
protected void createCachedAnimations(Map<String, Integer> map) {
    int i = 0;

    for (Map.Entry<String, Integer> entry : map.entrySet()) {
        String animationName = entry.getKey();
        int frameCounter = entry.getValue();

        // calculate duration per frame
        float durationPerFrame = this.sumDuration / frameCounter;

        // get regions
        Array<TextureAtlas.AtlasRegion> regions = this.atlas.findRegions(animationName);

        // create animation
        Animation<TextureRegion> anim = new Animation<>(durationPerFrame, regions, Animation.PlayMode.LOOP);

        // add animation to map
        this.animationMap.put(animationName, anim);

        i++;
    }
}
 
Example 17
Project: gdx-fireapp   File: Database.java   Source Code and License 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public <T, R extends T> void onDataChange(Class<T> dataType, DataChangeListener<R> listener)
{
    if (listener != null) {
        DataChangeValueListener<T, R> dataChangeListener = new DataChangeValueListener<>(dataType, listener);
        if (!valueEventListeners.containsKey(databasePath))
            valueEventListeners.put(databasePath, new Array<ValueEventListener>());
        valueEventListeners.get(databasePath).add(dataChangeListener);
        databaseReference().addValueEventListener(dataChangeListener);
    } else {
        Array<ValueEventListener> listeners = valueEventListeners.get(databasePath);
        for (ValueEventListener v : listeners) {
            databaseReference().removeEventListener(v);
        }
    }
    terminateOperation();
}
 
Example 18
Project: featurea   File: MyLwjglCanvas.java   Source Code and License 6 votes vote down vote up
public boolean executeRunnables() {
    Array var1 = this.runnables;
    synchronized (this.runnables) {
        int i = this.runnables.size - 1;

        while (true) {
            if (i < 0) {
                this.runnables.clear();
                break;
            }

            this.executedRunnables.addAll(new Runnable[]{(Runnable) this.runnables.get(i)});
            --i;
        }
    }

    if (this.executedRunnables.size == 0) {
        return false;
    } else {
        do {
            ((Runnable) this.executedRunnables.pop()).run();
        } while (this.executedRunnables.size > 0);

        return true;
    }
}
 
Example 19
Project: cocos2d-java   File: EventDispatcher.java   Source Code and License 5 votes vote down vote up
/** Sorts the listeners of specified type by scene graph priority */
    public void sortEventListenersOfSceneGraphPriority(final String listenerID, INode rootNode) {
        EventListenerVector listeners = getListeners(listenerID);
        
        if (listeners == null) {return;}
        Array<EventListener> sceneGraphListeners = listeners.getSceneGraphPriorityListeners();
        
        if (sceneGraphListeners == null) {return;}

        // Reset priority index
        _nodePriorityIndex = 0;
        _nodePriorityMap.clear();

        visitTarget(rootNode, true);
        
        // After sort: priority < 0, > 0
        sceneGraphListeners.sort(new Comparator<EventListener>() {
			@Override
			public int compare(EventListener l1, EventListener l2) {
				int p1 = _nodePriorityMap.get(l1._node);
				int p2 = _nodePriorityMap.get(l2._node);
				return p1 - p2;
			}
		});
//        std::sort(sceneGraphListeners->begin(), sceneGraphListeners->end(), [this](const EventListener* l1, const EventListener* l2) {
//            return _nodePriorityMap[l1->getAssociatedNode()] > _nodePriorityMap[l2->getAssociatedNode()];
//        });
        
//    #if DUMP_LISTENER_ITEM_PRIORITY_INFO
//        log("-----------------------------------");
//        for (auto& l : *sceneGraphListeners)
//        {
//            log("listener priority: node ([%s]%p), priority (%d)", typeid(*l->_node).name(), l->_node, _nodePriorityMap[l->_node]);
//        }
//    #endif
    }
 
Example 20
Project: jenjin   File: SkeletonActorPool.java   Source Code and License 5 votes vote down vote up
public SkeletonActorPool (SkeletonRenderer renderer, SkeletonData skeletonData, AnimationStateData stateData,
	int initialCapacity, int max) {
	super(initialCapacity, max);

	this.renderer = renderer;
	this.skeletonData = skeletonData;
	this.stateData = stateData;

	obtained = new Array(false, initialCapacity);

	skeletonPool = new Pool<Skeleton>(initialCapacity, max) {
		protected Skeleton newObject () {
			return new Skeleton(SkeletonActorPool.this.skeletonData);
		}

		protected void reset (Skeleton skeleton) {
			skeleton.setColor(Color.WHITE);
			skeleton.setFlip(false, false);
			skeleton.setSkin((Skin)null);
			skeleton.setSkin(SkeletonActorPool.this.skeletonData.getDefaultSkin());
			skeleton.setToSetupPose();
		}
	};

	statePool = new Pool<AnimationState>(initialCapacity, max) {
		protected AnimationState newObject () {
			return new AnimationState(SkeletonActorPool.this.stateData);
		}

		protected void reset (AnimationState state) {
			state.clearTracks();
			state.clearListeners();
		}
	};
}
 
Example 21
Project: cocos2d-java   File: EventDispatcher.java   Source Code and License 5 votes vote down vote up
private void cleanToRemovedListeners() {
	for(EventListener l : _toRemovedListeners) {
		
		EventListenerVector listeners = _listenerMap.get(l.getListenerID());
		if(listeners == null) {
			continue;
		}

        boolean find = false;
        Array<EventListener> fixedPriorityListeners = listeners.getFixedPriorityListeners();
        Array<EventListener> sceneGraphPriorityListeners = listeners.getSceneGraphPriorityListeners();

        if (sceneGraphPriorityListeners != null) {
        	if(sceneGraphPriorityListeners.removeValue(l, true)) {find = true;}
        }
        
        if (fixedPriorityListeners != null) {
        	if(fixedPriorityListeners.removeValue(l, true)) {find = true;}
        }

        if (find) {
            if (sceneGraphPriorityListeners != null && sceneGraphPriorityListeners.size <= 0) {
                listeners.clearSceneGraphListeners();
            }
            if (fixedPriorityListeners != null && fixedPriorityListeners.size <= 0) {
                listeners.clearFixedListeners();
            }
        }
	}
	_toRemovedListeners.clear();
}
 
Example 22
Project: Planet-Generator   File: SavingLoadingTests.java   Source Code and License 5 votes vote down vote up
@Test
public void testRingJson() {
    Array<Orbiter> array = new Array<>();
    int objectCount = 10;
    for(int i = 0; i < objectCount; i++) {
        array.add(new Orbiter(null, new Orbiter.OrbiterBlueprint()));
    }

    ColorGroup colorGroup = new ColorGroup()
            .add(Color.rgba8888(1, 0, 0, 1))
            .add(Color.rgba8888(0, 0, 1, 1));

    Ring saveRing = new Ring(array, colorGroup, 10, 50);
    saveRing.setAngularVelocity(100);
    saveRing.setXTilt(25);
    saveRing.setZTilt(50);

    String ringJson = json.toJson(saveRing);
    assertNotEquals("", ringJson);

    Ring loadRing = json.fromJson(Ring.class, ringJson);

    assertNotEquals(null, loadRing);
    assertEquals(10, loadRing.getMinimumRadius());
    assertEquals(50, loadRing.getMaximumRadius());
    assertEquals(100, loadRing.getAngularVelocity());
    assertEquals(25, loadRing.getXTilt());
    assertEquals(50, loadRing.getZTilt());
}
 
Example 23
Project: Mindustry   File: Saves.java   Source Code and License 5 votes vote down vote up
public void convertSaves(){
    Array<SaveSlot> invalid = new Array<>();

    for(SaveSlot slot : saves){
        if(!SaveIO.checkConvert(slot.index)){
            invalid.add(slot);
        }
    }

    saves.removeAll(invalid, true);
}
 
Example 24
Project: miniventure   File: Level.java   Source Code and License 5 votes vote down vote up
public Array<Tile> getAreaTiles(int xt, int yt, int radius, boolean includeCenter) {
	Array<Tile> tiles = new Array<>();
	for(int x = Math.max(0, xt-radius); x <= Math.min(width-1, xt+radius); x++) {
		for(int y = Math.max(0, yt-radius); y <= Math.min(height-1, yt+radius); y++) {
			tiles.add(this.tiles[x][y]);
		}
	}
	
	if(!includeCenter)
		tiles.removeValue(this.tiles[xt][yt], true);
	
	return tiles;
}
 
Example 25
Project: jenjin   File: SkeletonBounds.java   Source Code and License 5 votes vote down vote up
/** Clears any previous polygons, finds all visible bounding box attachments, and computes the world vertices for each bounding
 * box's polygon.
 * @param updateAabb If true, the axis aligned bounding box containing all the polygons is computed. If false, the
 *           SkeletonBounds AABB methods will always return true. */
public void update (Skeleton skeleton, boolean updateAabb) {
	if (skeleton == null) throw new IllegalArgumentException("skeleton cannot be null.");
	Array<BoundingBoxAttachment> boundingBoxes = this.boundingBoxes;
	Array<FloatArray> polygons = this.polygons;
	Array<Slot> slots = skeleton.slots;
	int slotCount = slots.size;

	boundingBoxes.clear();
	polygonPool.freeAll(polygons);
	polygons.clear();

	for (int i = 0; i < slotCount; i++) {
		Slot slot = slots.get(i);
		Attachment attachment = slot.attachment;
		if (attachment instanceof BoundingBoxAttachment) {
			BoundingBoxAttachment boundingBox = (BoundingBoxAttachment)attachment;
			boundingBoxes.add(boundingBox);

			FloatArray polygon = polygonPool.obtain();
			polygons.add(polygon);
			boundingBox.computeWorldVertices(slot, polygon.setSize(boundingBox.getWorldVerticesLength()));
		}
	}

	if (updateAabb)
		aabbCompute();
	else {
		minX = Integer.MIN_VALUE;
		minY = Integer.MIN_VALUE;
		maxX = Integer.MAX_VALUE;
		maxY = Integer.MAX_VALUE;
	}
}
 
Example 26
Project: StarshipFighters   File: Level.java   Source Code and License 5 votes vote down vote up
public void init() {
	
	// Load TMX Map
	spawnPoints = new Array<Vector2>();
	tiledMap = new TmxMapLoader().load(mapName);
	spawnLayer = tiledMap.getLayers().get("BasicAlienSpawn");
	loadSpawnLocations(spawnLayer);
}
 
Example 27
Project: enklave   File: SmartFontGenerator.java   Source Code and License 5 votes vote down vote up
/** Convenience method for generating a font, and then writing the fnt and png files.
 * Writing a generated font to files allows the possibility of only generating the fonts when they are missing, otherwise
 * loading from a previously generated file.
 * @param fontFile
 * @param fontSize
 */
private BitmapFont generateFontWriteFiles(String fontName, FileHandle fontFile, int fontSize, int pageWidth, int pageHeight) {
    FreeTypeFontGenerator generator = new FreeTypeFontGenerator(fontFile);

    PixmapPacker packer = new PixmapPacker(pageWidth, pageHeight, Pixmap.Format.RGBA8888, 2, false);
    FreeTypeFontGenerator.FreeTypeFontParameter parameter = new FreeTypeFontGenerator.FreeTypeFontParameter();
    parameter.size = fontSize;
    parameter.characters = FreeTypeFontGenerator.DEFAULT_CHARS;
    parameter.packer = packer;
    FreeTypeFontGenerator.FreeTypeBitmapFontData fontData = generator.generateData(parameter);//(fontSize, FreeTypeFontGenerator.DEFAULT_CHARS, false, packer);
    Array<PixmapPacker.Page> pages = packer.getPages();
    Array<TextureRegion> texRegions = new Array<TextureRegion>(pageSize);
    for (int i=0; i<pages.size; i++) {
        PixmapPacker.Page p = pages.get(i);
        Texture tex = new Texture(new PixmapTextureData(p.getPixmap(), p.getPixmap().getFormat(), false, false, true)) {
            @Override
            public void dispose () {
                super.dispose();
                getTextureData().consumePixmap().dispose();
            }
        };
        tex.setFilter(Texture.TextureFilter.Nearest, Texture.TextureFilter.Nearest);
        texRegions.add(new TextureRegion(tex));
    }
    BitmapFont font = new BitmapFont(fontData,texRegions,false); //fontData, texRegions, false);
    saveFontToFile(font, fontSize, fontName, packer);
    generator.dispose();
    packer.dispose();
    return font;
}
 
Example 28
Project: FlappySpinner   File: Ground.java   Source Code and License 5 votes vote down vote up
public Ground(Array<Body> bodies) {

        ground = bodies.first();//first item
        sky = bodies.peek();//last item

        textureRegionGround = AssetsManager.getTextureRegion(Constants.GROUND_IMAGE_NAME);
        textureRegionSky = AssetsManager.getTextureRegion(Constants.SKY_IMAGE_NAME);

        groundPositions1 = new Vector2(0, 0);
        groundPositions2 = new Vector2(Constants.WIDTH, 0);
    }
 
Example 29
Project: cocos2d-java   File: FileUtils.java   Source Code and License 5 votes vote down vote up
/**
 * 设置搜索路径 搜索优先级:从前到后
 * @param searchPaths
 */
public void setSearchPaths(Array<FullFilePath> searchPaths) {
	_searchPathArray.clear();
	for(FullFilePath f : searchPaths) {
		this._searchPathArray.add(f);
	}
}
 
Example 30
Project: Planet-Generator   File: Ring.java   Source Code and License 5 votes vote down vote up
@Override
public void read(Json json, JsonValue jsonData) {
    minRadius = json.readValue("minimumRadius", Float.class, jsonData);
    maxRadius = json.readValue("maximumRadius", Float.class, jsonData);
    angularVelocity = json.readValue("angularVelocity", Float.class, jsonData);
    zTilt = json.readValue("zTilt", Float.class, jsonData);
    xTilt = json.readValue("xTilt", Float.class, jsonData);
    colors = json.readValue("colorGroup", ColorGroup.class, jsonData);

    this.baseObjectCount = json.readValue("objectCount", Integer.class, jsonData);
    objects = new Array<>(baseObjectCount);
}
 
Example 31
Project: cocos2d-java   File: PhysicsObject.java   Source Code and License 5 votes vote down vote up
public PhysicsGenerator addGenerator(PhysicsGenerator generator, boolean checkContains) {
	if(generatorList == null) {
		generatorList = new Array<PhysicsGenerator>(2);
	}
	checkGeneratorCount();
	if(checkContains) {
		if(findGenerator(generator)) {
			CCLog.engine("PhysicsObject", "generator already exist! ");
			return generator;
		}
	} 
	generatorList.add(generator);
	return generator;
}
 
Example 32
Project: Planet-Generator   File: EditorUI.java   Source Code and License 5 votes vote down vote up
private void createStarsClicked() {
    if(starEditor == null || starEditor.hasDeleteBeenPressed()) {
        starEditor = new StarEditor(scene, "Stars");
        addObjectEditor(starEditor);
    } else {
        starEditor.deleteObjects();
    }

    Array<Star> stars = scene.getObjectGenerator().createStars();
    starEditor.setStars(stars);
}
 
Example 33
Project: summer17-android   File: Animation.java   Source Code and License 5 votes vote down vote up
public Animation(TextureRegion region, int frameCount, float cycleTime) {
    frames = new Array<TextureRegion>();
    int frameWidth = region.getRegionWidth() / frameCount;
    for ( int i = 0; i < frameCount; i++){
        frames.add(new TextureRegion(region, i * frameWidth, 0, frameWidth, region.getRegionHeight()));
    }
    this.frameCount = frameCount;
    maxFrameTime = cycleTime / frameCount;
    frame = 0;
}
 
Example 34
Project: KyperBox   File: QuadTree.java   Source Code and License 5 votes vote down vote up
public Quad(QuadTree manager) {
	this.pool = manager.getPool();
	this.manager = manager;
	quad_objects = new Array<GameObject>();
	bounds = new Rectangle();
	quads = new Quad[4];
}
 
Example 35
Project: bobbybird   File: ObstacleManager.java   Source Code and License 5 votes vote down vote up
@Override
public void create() {
    Array<String> names = getCore().getImagePacks().get(DATA_PATH + "/obstacles");
    obstacleTexture = getCore().getAtlas().findRegion(names.random());
    obstacleFlipped = new TextureRegion(obstacleTexture);
    obstacleFlipped.flip(false, true);
    timer = (obstacleTexture.getRegionWidth() + GameState.OBSTACLE_GAP) / GameState.SCROLL_SPEED;
}
 
Example 36
Project: Cubes_2   File: WorldGraphicsPools.java   Source Code and License 5 votes vote down vote up
@Override
public void freeAll(Array<T> array) {
	if (array == null)
		throw new IllegalArgumentException("array cannot be null");
	for (T t : array) {
		free(t);
	}
}
 
Example 37
Project: Mindustry   File: LiquidPowerGenerator.java   Source Code and License 5 votes vote down vote up
@Override
public void getStats(Array<String> list){
	super.getStats(list);
	list.add("[liquidinfo]Liquid Capacity: " + (int)liquidCapacity);
	list.add("[liquidinfo]Power/Liquid: " + Strings.toFixed(powerPerLiquid, 2) + " power/liquid");
	list.add("[liquidinfo]Max liquid/second: " + Strings.toFixed(maxLiquidGenerate*60f, 2) + " liquid/s");
	list.add("[liquidinfo]Input: " + generateLiquid);
}
 
Example 38
Project: miniventure   File: Tile.java   Source Code and License 5 votes vote down vote up
/** @noinspection UnusedReturnValue*/
public static Array<Tile> sortByDistance(Array<Tile> tiles, final Vector2 position) {
	tiles.sort((t1, t2) -> {
		float t1diff = position.dst(t1.getBounds().getCenter(new Vector2()));
		float t2diff = position.dst(t2.getBounds().getCenter(new Vector2()));
		return Float.compare(t1diff, t2diff);
	});
	
	return tiles;
}
 
Example 39
Project: gdx-cclibs   File: BatchablePreparation.java   Source Code and License 5 votes vote down vote up
/** Generate vertex attributes suitable for multi-texturing and vertex color. 32 bit floats are used for each position
 * component and texture coordinate. The four color components are packed into a single 32 bit float.
 * @param textureCount The number of textures to support.
 * @param position3D Whether the position attribute should include a Z component.
 * @param textureCoordinates3D Whether the texture coordinate attribute(s) should include a third component.
 * @param attributes The array to add the vertex attributes to. They are added with position and color in the first two
 *           available positions, followed by texture coordinates. */
public static void addBaseAttributes (Array<VertexAttribute> attributes, int textureCount, boolean position3D,
	boolean textureCoordinates3D) {
	attributes.add(new VertexAttribute(Usage.Position, position3D ? 3 : 2, ShaderProgram.POSITION_ATTRIBUTE));
	attributes.add(new VertexAttribute(Usage.ColorPacked, 4, ShaderProgram.COLOR_ATTRIBUTE));
	for (int i = 0; i < textureCount; i++) {
		attributes.add(
			new VertexAttribute(Usage.TextureCoordinates, textureCoordinates3D ? 3 : 2, ShaderProgram.TEXCOORD_ATTRIBUTE + i, i));
	}
}
 
Example 40
Project: jenjin   File: Skeleton.java   Source Code and License 5 votes vote down vote up
/**
 * Finds a bone by comparing each bone's name. It is more efficient to cache the results of this method than to call it
 * multiple times.
 *
 * @return May be null.
 */
public Bone findBone(String boneName) {
    if (boneName == null) throw new IllegalArgumentException("boneName cannot be null.");
    Array<Bone> bones = this.bones;
    for (int i = 0, n = bones.size; i < n; i++) {
        Bone bone = bones.get(i);
        if (bone.data.name.equals(boneName)) return bone;
    }
    return null;
}
 
Example 41
Project: Tower-Defense-Galaxy   File: VRContext.java   Source Code and License 5 votes vote down vote up
/**
 * @return all currently connected {@link VRDevice} instances.
 */
public Array<VRDevice> getDevices() {
	Array<VRDevice> result = new Array<VRDevice>();
	for (VRDevice d: devices) {
		if (d != null) result.add(d);
	}
	return result;
}
 
Example 42
Project: miniventure   File: WorldObject.java   Source Code and License 5 votes vote down vote up
@Nullable
default Tile getClosestTile(@NotNull Array<Tile> tiles) {
	if(tiles.size == 0) return null;
	
	Vector2 center = new Vector2();
	getBounds().getCenter(center);
	HashMap<Vector2, Tile> tileMap = new HashMap<>();
	for(Tile t: tiles)
		tileMap.put(new Vector2(t.getCenterX(), t.getCenterY()), t);
	
	Array<Vector2> tileCenters = new Array<>(tileMap.keySet().toArray(new Vector2[tileMap.size()]));
	tileCenters.sort((v1, v2) -> (int) (center.dst2(v1) - center.dst2(v2))); // sort, so the first one in the list is the closest one
	
	return tileMap.get(tileCenters.get(0));
}
 
Example 43
Project: KyperBox   File: GameState.java   Source Code and License 5 votes vote down vote up
public void unloadFonts() {
	Array<BitmapFont> fvalues = fonts.values().toArray();
	AssetManager am = game.getAssetManager();
	unload_helper.clear();
	for (int i = 0; i < fvalues.size; i++) {
		unload_helper.add(fvalues.get(i).getData().fontFile.path());
	}

	fvalues.clear();
	for (int i = 0; i < unload_helper.size; i++) {
		am.unload(unload_helper.get(i));
	}
}
 
Example 44
Project: Mindustry   File: Turret.java   Source Code and License 5 votes vote down vote up
@Override
public void getStats(Array<String> list){
	super.getStats(list);
	if(ammo != null) list.add("[turretinfo]Ammo: " + ammo);
	if(ammo != null) list.add("[turretinfo]Ammo Capacity: " + maxammo);
	if(ammo != null) list.add("[turretinfo]Ammo/Item: " + ammoMultiplier);
	list.add("[turretinfo]Range: " + (int)range);
	list.add("[turretinfo]Inaccuracy: " + (int)inaccuracy);
	list.add("[turretinfo]Damage/Shot: " + bullet.damage);
	list.add("[turretinfo]Shots/Second: " + Strings.toFixed(60f/reload, 1));
	list.add("[turretinfo]Shots: " + shots);
}
 
Example 45
Project: StarshipFighters   File: BasicAlien.java   Source Code and License 5 votes vote down vote up
public BasicAlien(float x, float y, float dx, float dy, long bulletCooldown, float bulletShootSpeed,
		Array<EnemyBullets> listOfEnemyBullets, int damageValue, PlayState playState) {
	super(x, y, dx, dy);

	// GamePlay
	this.x = x;
	this.y = y;
	this.dx = dx;
	this.dy = dy;
	this.bulletCooldown = bulletCooldown;
	this.enemyBulletSpeed = bulletShootSpeed;
	this.listofEnemyBullets = listOfEnemyBullets;
	this.damageValue = damageValue;
	healthbar = 100;
	this.playState = playState;

	// GamePlay Starting Positions
	initialX = x;
	initialY = y;

	// Graphics
	pathName = "data/spaceships/BasicEnemy.png";

	// Limits
	maxSpeed = 10;
	minimumSpeed = maxSpeed * -1;

	// Load Initial enemy data
	init();
}
 
Example 46
Project: miniventure   File: Level.java   Source Code and License 5 votes vote down vote up
public void render(Rectangle renderSpace, SpriteBatch batch, float delta) {
	// the game renders around the main player. For now, the level shall be the same size as the screen, so no camera fanciness or coordinate manipulation is needed.
	
	//batch.disableBlending(); // this prevents alpha from being rendered, which gives a performance boost. When drawing tiles, we don't need alpha (yet), so we'll disable it.
	//for(Tile[] tiles: this.tiles)
		for(Tile tile: getOverlappingTiles(renderSpace))
			tile.render(batch, delta);
	//batch.enableBlending(); // re-enable alpha for the drawing of entities.
	
	Array<Entity> overlapping = getOverlappingEntities(renderSpace);
	//System.out.println("entities being rendered: " + overlapping);
	for(Entity entity: overlapping)
		entity.render(batch, delta);
}
 
Example 47
Project: Planet-Generator   File: CloudEditor.java   Source Code and License 5 votes vote down vote up
public void setClouds(Array<Cloud> clouds) {
    this.clouds = new Array<>(clouds);
    count.setValue(this.clouds.size);

    if(this.clouds.size > 0) {
        velocitySlider.setValue(this.clouds.first().getAngularVelocity());
    } else {
        velocitySlider.setValue(0);
    }
}
 
Example 48
Project: Mindustry   File: Sorter.java   Source Code and License 5 votes vote down vote up
@Override
public void buildTable(Tile tile, Table table){
	SorterEntity entity = tile.entity();

	Array<Item> items = Item.getAllItems();

	ButtonGroup<ImageButton> group = new ButtonGroup<>();
	Table cont = new Table();
	cont.margin(4);
	cont.marginBottom(5);

	cont.add().colspan(4).height(105f);
	cont.row();

	for(int i = 0; i < items.size; i ++){
		final int f = i;
		ImageButton button = cont.addImageButton("white", "toggle", 24, () -> {
			entity.sortItem = items.get(f);
			setConfigure(tile, (byte)f);
		}).size(38, 42).padBottom(-5.1f).group(group).get();
		button.getStyle().imageUp = new TextureRegionDrawable(new TextureRegion(Draw.region("icon-"+items.get(i).name)));
		button.setChecked(entity.sortItem.id == f);

		if(i%4 == 3){
			cont.row();
		}
	}

	table.add(cont);
}
 
Example 49
Project: cocos2d-java   File: EventDispatcher.java   Source Code and License 4 votes vote down vote up
/** Remove a listener
     *  @param listener The specified event listener which needs to be removed.
     */
    public void removeEventListener(EventListener listener) {
    	if(listener == null) {return;}
    	
    	if(_toRemovedListeners.contains(listener)) {return;}
    	
    	boolean isFound = false;
    	
    	Iterator<Entry<String, EventListenerVector>> it = _listenerMap.entrySet().iterator();
    	while(it.hasNext()) {
    		EventListenerVector listeners = it.next().getValue();
    		Array<EventListener> fixedPriorityListeners = listeners.getFixedPriorityListeners();
    		Array<EventListener> sceneGraphPriorityListeners = listeners.getSceneGraphPriorityListeners();
    		
    		if(removeListenerInVector(sceneGraphPriorityListeners, listener)) {
    			isFound = true;
    		}
    		if(isFound) {
                // fixed #4160: Dirty flag need to be updated after listeners were removed.
    			setDirty(listener.getListenerID(), DirtyFlag.SCENE_GRAPH_PRIORITY);
    		} else {
    			if(removeListenerInVector(fixedPriorityListeners, listener)) {
    				isFound = true;
    			}
    			if(isFound) {
    				setDirty(listener.getListenerID(), DirtyFlag.FIXED_PRIORITY);
    			}
    		}
//    #if CC_NODE_DEBUG_VERIFY_EVENT_LISTENERS
//            CCASSERT(_inDispatch != 0 ||
//                     !sceneGraphPriorityListeners ||
//                     std::count(sceneGraphPriorityListeners->begin(), sceneGraphPriorityListeners->end(), listener) == 0,
//                     "Listener should be in no lists after this is done if we're not currently in dispatch mode.");
//                
//            CCASSERT(_inDispatch != 0 ||
//                     !fixedPriorityListeners ||
//                     std::count(fixedPriorityListeners->begin(), fixedPriorityListeners->end(), listener) == 0,
//                     "Listener should be in no lists after this is done if we're not currently in dispatch mode.");
//    #endif
            if (listeners.empty()) {
                _priorityDirtyFlagMap.remove(listener.getListenerID());
                it.remove();
            }
            
            if (isFound) {break;}
        }

        if (isFound) {
//            releaseListener(listener);
        } else {
        	if(_toAddedListeners.remove(listener)) {
	        	listener.setRegistered(false);
        	}
        }
    }
 
Example 50
Project: libGDX-RTL-Language   File: ArGlyphComplex.java   Source Code and License 4 votes vote down vote up
public ArGlyphComplex(char complexChar) {
    super(complexChar, true);
    simpleGlyphs = new Array<ArGlyph>();
}
 
Example 51
Project: bobbybird   File: GameState.java   Source Code and License 4 votes vote down vote up
private TextureRegion getGround() {
    Array<String> names = getCore().getImagePacks().get(DATA_PATH + "/grounds");
    return getCore().getAtlas().findRegion(names.random());
}
 
Example 52
Project: KyperBox   File: GameInput.java   Source Code and License 4 votes vote down vote up
public Array<String> getAllInputs(){
	return input_check;
}
 
Example 53
Project: jenjin   File: SkeletonData.java   Source Code and License 4 votes vote down vote up
/** The skeleton's IK constraints. */
public Array<IkConstraintData> getIkConstraints () {
	return ikConstraints;
}
 
Example 54
Project: KyperBox   File: PlatformerController.java   Source Code and License 4 votes vote down vote up
@Override
public void update(GameObject object, float delta) {
	on_ground = false;
	if(collision_control==null) {
		collision_control = object.getController(CollisionController.class);
	}
	
	switch(state) {
	case STAND:
		GameObject collision = null;
		if(collision_control!=null)
		  collision = collision_control.collisionWithOffset(object,0,-1);
		
		if((collision == null)&& object.getCollisionBounds().y > 0) {
				state = PlatformState.FALL;
		}else if(collision!=null){
			PlatformerController cp = collision.getController(PlatformerController.class);
			if(cp!=null && cp.on_ground)
				on_ground = true;
			else
				state = PlatformState.FALL;
		}else {
			on_ground = true;
		}
		break;
	case JUMP: 
		if(jumping) {
			object.setVelocity(object.getVelocity().x, object.getVelocity().y+gravity);
		}else {
			object.setVelocity(object.getVelocity().x, Math.min(object.getVelocity().y+gravity,min_jump_speed));
		}
		
		if(object.getVelocity().y < 0) 
			state =PlatformState.FALL;
		break;
	case FALL: 
		object.setVelocity(object.getVelocity().x, object.getVelocity().y+gravity);
		if(object.getY() < 0) {
			on_ground = true;
			object.setPosition(object.getX(), 0);
			state = PlatformState.STAND;
			stopY();
		}
		if(collision_control!=null) {
			
			Array<CollisionData> col_data = collision_control.getCollisions();
			for (int i = 0; i < col_data.size; i++) {
				CollisionData cd = col_data.get(i);
				PlatformerController tpc = cd.getTarget().getController(PlatformerController.class);
				if(tpc == null)
					continue;
				float cd_y = cd.getOverlapBox().y;
				float cd_h = cd.getOverlapBox().height;
				if(tpc.on_ground && cd_y+cd_h > object.getCollisionBounds().y) {
					object.setPosition(object.getX(), cd_y+cd_h);
					stopY();
					on_ground = true;
					state = PlatformState.STAND;
				}
			}
		}
			
		break;
	default:
		break;
	}
	jumping = false;
	walking = false;
}
 
Example 55
Project: jenjin   File: IkConstraint.java   Source Code and License 4 votes vote down vote up
/** The bones that will be modified by this IK constraint. */
public Array<Bone> getBones () {
	return bones;
}
 
Example 56
Project: libgdx_ui_editor   File: SelectGroup.java   Source Code and License 4 votes vote down vote up
public void addAllSelectActor(Array<Actor> actors){
    selection.addAll(actors);
    initLayout();
}
 
Example 57
Project: Planet-Generator   File: Cloud.java   Source Code and License 4 votes vote down vote up
public Cloud(Array<Orbiter> cloudObjects) {
    this.cloudObjects = cloudObjects;
    color = cloudObjects.first().getColor();
}
 
Example 58
Project: Mindustry   File: Net.java   Source Code and License 4 votes vote down vote up
/**Returns a list of all connections IDs.*/
public static Array<? extends NetConnection> getConnections(){
	return serverProvider.getConnections();
}
 
Example 59
Project: cocos2d-java   File: ActionManager.java   Source Code and License 4 votes vote down vote up
/** Main loop of ActionManager.
    * @param dt    In seconds.
    */
   public boolean update(float dt) {
	   updateToAddArray();
	   
	   _lock = true;
	   
	   //remove elements
	   Iterator<struct_hashElement> it = _elements.iterator();
	   while(it.hasNext()) {
		   _currentTarget = it.next();
		   if(_currentTarget.removeFlag) {
			   it.remove();
		   }
		   
		   if(!_currentTarget.paused) {
			   // 更新时候需要从后向前——可能在过程中执行删除操作
			   Array<IAction> actions = _currentTarget.actions;
//			   actions.t
			   for(int i = actions.size - 1; i >= 0; --i) {
				   IAction a = actions.get(i);
				   
				   //remove when (attach = false)
				   if(!a.isAttached()) {
					   unsafeRemoveAction(a);
//					   actions.removeIndex(i);
					   continue;
				   }
				   
				   a.step(dt * 0.001f);	//ms to s
				   
				   if(a.isDone()) {
					   a.stop();
//					   _currentTarget.currentAction = null;
					   unsafeRemoveAction(a);
				   }
////				   if(_currentTarget.currentActionSalvaged) {
////					   _currentTarget.currentAction = null;
//				   } else 
//					   if(_currentTarget.currentAction.isDone()) {
//					   a.stop();
//					   _currentTarget.currentAction = null;
//					   removeAction(a);
//				   }
				   _currentTarget.currentAction = null;
			   }
		   }
//		   if(_currentTargetSalvaged && _currentTarget.actions.size <= 0) {
//			   deleteHashElement(_currentTarget);
//		   }
	   }
	   
	   
	   _currentTarget = null;
	   _lock = false;
	   
	   return false;
   }
 
Example 60
Project: Onyx   File: GameScreenManager.java   Source Code and License 4 votes vote down vote up
/**
 * Sets the {@link Array<PlayerEntity>} instance used by {@link GameScreen}
 * @param players the player array
 */
public static void setPlayers(Array<PlayerEntity> players) {
    check();
    //// TODO: 22-04-2017 Add check for data 
    GameScreenManager.players = players;
}