Java Code Examples for com.badlogic.gdx.math.Vector2

The following are top voted examples for showing how to use com.badlogic.gdx.math.Vector2. 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: Mindustry   File: GestureHandler.java   Source Code and License 6 votes vote down vote up
@Override
public boolean pinch (Vector2 initialPointer1, Vector2 initialPointer2, Vector2 pointer1, Vector2 pointer2) {
	if(control.getInput().recipe == null && !control.getInput().breakMode.lockCamera)
		return false;
	
	if(pinch1.x < 0){
		pinch1.set(initialPointer1);
		pinch2.set(initialPointer2);
	}
	
	Vector2 vec = (vector.set(pointer1).add(pointer2).scl(0.5f)).sub(pinch1.add(pinch2).scl(0.5f));
	
	player.x -= vec.x*Core.camera.zoom/Core.cameraScale;
	player.y += vec.y*Core.camera.zoom/Core.cameraScale;
	
	pinch1.set(pointer1);
	pinch2.set(pointer2);
	
	return false;
}
 
Example 2
Project: cocos2d-java   File: Base2D.java   Source Code and License 6 votes vote down vote up
/**
 * 创建限定双方向速度的限制器
 * 
 * @param limitX (limitX >= 0)
 * @param limitY (limitY >= 0)
 * @return
 */
public static VelocityLimitListener create(final float limitX, final float limitY) {
	return new VelocityLimitListener() {
		@Override
		public void onVelocity(Vector2 velocity) {
			if(velocity.y > limitY) {
				velocity.y = limitY;
			} else if(velocity.y < -limitY) {
				velocity.y = -limitY;
			}
			
			if(velocity.x > limitX) {
				velocity.x = limitX;
			} else if(velocity.x < -limitX) {
				velocity.x = -limitX;
			}
		}
	};
}
 
Example 3
Project: enklave   File: DrawAttachers.java   Source Code and License 6 votes vote down vote up
public float getYmax() {
    float ymax=-1;
    if (arrayAttachers.length > 7) {
        ymax = arrayAttachers[6].findActor("frame").localToStageCoordinates(new Vector2(0, 0)).y;
        ymax = ymax + arrayAttachers[6].findActor("frame").getWidth() * 0.5f;
    } else {
        if(arrayAttachers.length>0)
            ymax = arrayAttachers[arrayAttachers.length - 1].findActor("frame").localToStageCoordinates(new Vector2(0, 0)).y;
        if (arrayAttachers.length < 4 && arrayAttachers.length > 0)
            ymax = ymax + arrayAttachers[arrayAttachers.length - 1].findActor("frame").getHeight();
        else if (arrayAttachers.length > 3)
            ymax = ymax + arrayAttachers[arrayAttachers.length - 1].findActor("frame").getHeight() * 0.8f;
        else if (arrayAttachers.length > 5)
            ymax = ymax + arrayAttachers[arrayAttachers.length - 1].findActor("frame").getHeight() * 0.5f;
    }
    return ymax;
}
 
Example 4
Project: ExamensArbeteTD   File: EntityFactory.java   Source Code and License 6 votes vote down vote up
public void createCoinEntity(float x, float y, int moneyValue) {
	Entity entity = new Entity();
	OffsetComponent ocomp = new OffsetComponent(16, 16);
	SkeletonComponent scomp = new SkeletonComponent(Assets.coinSkeleton);
	TimeComponent tcomp = new TimeComponent(0.5f);
	VelocityComponent vcomp = new VelocityComponent(25f);
	PositionComponent pcomp = new PositionComponent(new Vector2(x, y));
	MoneyComponent mcomp = new MoneyComponent(moneyValue);
	RenderableComponent rcomp = new RenderableComponent();
	scomp.animationState.setData(Assets.coinAnimationState.getData());
	entity.add(pcomp)//
			.add(vcomp)//
			.add(tcomp)//
			.add(scomp)//
			.add(ocomp)//
			.add(mcomp)//
			.add(rcomp);
	_engine.addEntity(entity);
}
 
Example 5
Project: TH902   File: AIS1L4Boss.java   Source Code and License 6 votes vote down vote up
public void part3() {
	Entity proj = BaseProjectile.Create(new Vector2(MathUtils.random(0, 560), 720), BulletType.FormCircleLightM, MathUtils.randomBoolean() ? BulletType.ColorOrange : BulletType.ColorBlue);
	final Transform ptransform = proj.GetComponent(Transform.class);
	proj.AddComponent(new MoveFunction(MoveFunctionTarget.ACCEL, MoveFunctionType.ASSIGNMENT, new IMoveFunction() {
		int flag = 2;
		int bounce = MathUtils.random(250, 500);
		@Override
		public Vector2 getTargetVal(int time) {
			if (flag > 0 && Math.abs(ptransform.position.y - bounce) < 30) {
				final int m = flag * 8;
				flag--;
				bounce -= 90;
				return vct2_tmp1.set(0.001f, m);
			}
			return vct2_tmp1.set(0.001f, -0.1f);
		}
	}));
	proj.AddComponent(new EnemyJudgeCircle(15));
}
 
Example 6
Project: cocos2d-java   File: Widget.java   Source Code and License 6 votes vote down vote up
/**
 * Set the percent(x,y) of the widget in OpenGL coordinates
 *
 * @param percent  The percent (x,y) of the widget in OpenGL coordinates
 */
public void setPositionPercent(Vector2 percent) {
	if (_usingLayoutComponent) {
		LayoutComponent component = this.getOrCreateLayoutComponent();
        component.setPositionPercentX(percent.x);
        component.setPositionPercentY(percent.y);
        component.refreshLayout();
    }
    else
    {
        _positionPercent.set(percent); 
        if (_running){
            Widget widgetParent = getWidgetParent();
            if (widgetParent != null) {
                Size parentSize = widgetParent.getContentSize();
                setPosition(Math.abs(parentSize.width * _positionPercent.x), Math.abs(parentSize.height * _positionPercent.y));
            }
        }
    }
}
 
Example 7
Project: GDX-Engine   File: PhysicsManager.java   Source Code and License 6 votes vote down vote up
/**
    * create Revolute Joint
    */
   public RevoluteJoint createRevoluteJoint(Body bodyA, Body bodyB,
    Vector2 jointPositionA, Vector2 jointPositionB,
    boolean enabledMotor, int maxMotorTorque, int motorSpeed) {
RevoluteJointDef rJoint = new RevoluteJointDef();
rJoint.bodyA = bodyA;
rJoint.bodyB = bodyB;
rJoint.localAnchorA.set(jointPositionA.x * WORLD_TO_BOX,
	jointPositionA.y * WORLD_TO_BOX);
rJoint.localAnchorB.set(jointPositionB.x * WORLD_TO_BOX,
	jointPositionB.y * WORLD_TO_BOX);

rJoint.enableMotor = enabledMotor;
rJoint.maxMotorTorque = maxMotorTorque;
rJoint.motorSpeed = motorSpeed;

RevoluteJoint joint = (RevoluteJoint) world.createJoint(rJoint);
return joint;
   }
 
Example 8
Project: homescreenarcade   File: WallElement.java   Source Code and License 6 votes vote down vote up
@Override public void handleCollision(Ball ball, Body bodyHit, Field field) {
    if (retractWhenHit) {
        this.setRetracted(true);
    }

    if (killBall) {
        field.removeBall(ball);
    }
    else {
        Vector2 impulse = this.impulseForBall(ball);
        if (impulse!=null) {
            ball.applyLinearImpulse(impulse);
            flashForFrames(3);
        }
    }
}
 
Example 9
Project: odb-little-fortune-planet   File: DrawingSystem.java   Source Code and License 6 votes vote down vote up
private void draw(int x, int y, EntityType entityType) {
    switch (entityType) {
        case ALIEN:
            planetCreationSystem.spawnDude(x, y).massInverse(true).alien();
            break;
        case ICBM:
            cardScriptSystem.spawnStructure("icbm", G.LAYER_STRUCTURES_FOREGROUND)
                    .explosiveYield(MathUtils.random(5,10)).pos(x, y);
            break;
        case SKYSCRAPER:
            cardScriptSystem.spawnStructure("skyscraper" + MathUtils.random(7), G.LAYER_STRUCTURES_BACKGROUND).pos(x, y);
            break;
        case DOLPHIN:
            E e = planetCreationSystem.spawnDude(x, y);
            Vector2 gravityVector = v.set(e.planetboundGravity()).rotate(180f);
            e
                    .dolphinized()
                    .physicsVr(1000f)
                    .physicsVx(gravityVector.x * 100f)
                    .physicsVy(gravityVector.y * 100f);
            break;
        case DUDE:
            planetCreationSystem.spawnDude(x, y).orientToGravityIgnoreFloor(false);
            break;
    }
}
 
Example 10
Project: TH902   File: CharacterSelectScreen.java   Source Code and License 6 votes vote down vote up
@Override
public void show() {
	super.show();
	Entity characterSelectScreenEntity = Entity.Create();
	Entity selectCharacter = Entity.Create();
	
	characterSelectScreenEntity.AddComponent(new Transform(new Vector2(480, 360)));
	selectCharacter.AddComponent(new Transform(new Vector2(600, 600)));
	
	
	characterSelectScreenEntity.AddComponent(new ImageRenderer(ResourceManager.textures.get("CharacterSelect"), 0));
	selectCharacter.AddComponent(new ImageRenderer(ResourceManager.textures.get("SelectCharacter"), 1));
	KeyboardSelectable selectable = new KeyboardSelectable(() -> {
		GameMain.instance.setScreen(new FightScreen());
	});
	selectable.isSelected = true;
	selectCharacter.AddComponent(selectable);
}
 
Example 11
Project: arcadelegends-gg   File: Character.java   Source Code and License 6 votes vote down vote up
public Character() {
    this.cooldownTimer = new float[5];
    this.castTimer = new float[5];
    this.casting = new boolean[5];
    this.extraData = new Object[5];
    this.cooldowns = new float[5];
    this.costs = new float[5];
    this.random = new Random();

    finishedAttack = true;

    vectorPool = new Pool<Vector2>() {
        @Override
        protected Vector2 newObject() {
            return new Vector2();
        }

        @Override
        protected void reset(Vector2 object) {
            object.setZero();
        }
    };
}
 
Example 12
Project: cocos2d-java   File: CollideAlgorithms.java   Source Code and License 6 votes vote down vote up
/**相交测试 
 * 多边形与AABB
 * @param A
 * @param B
 * @param MTD
 * @return  */
public static final boolean Intersect(final Polygon A,final AABBShape B,
		final Vector2 positionA, final Vector2 positionB){
	axisX.set(1,0);
	axisY.set(0,1);
	Vector2 tempE=null;
	//用这个不用单独求0的情况
	for(int j=A.getPoints().length-1, i=0; i<A.getPoints().length;
			j=i, i++) {
		tempE=A.getPoints()[i].sub(A.getPoints()[j]); 
		if (axisSeparatePolygonsMTD(new Vector2(-tempE.y, tempE.x), A, B, positionA, positionB)) 
			return false; 
	}
	if (axisSeparatePolygonsMTDX(axisX, A, B, positionA, positionB)) 
		return false; 
	if (axisSeparatePolygonsMTDY(axisY, A, B, positionA, positionB)) 
		return false; 
	return true;
}
 
Example 13
Project: water2d-libgdx   File: IntersectionUtils.java   Source Code and License 6 votes vote down vote up
/**
 * Because the algorithm is based on vertices, and the circles do not have vertices, we create a square around it.
 * @param fixture Circle fixture
 * @return A square instead of the circle
 */
private static PolygonShape circleToSquare(Fixture fixture) {
	Vector2 position = fixture.getBody().getLocalCenter();
	float x = position.x;
	float y = position .y;
	float radius = fixture.getShape().getRadius();
	
	PolygonShape octagon = new PolygonShape();
	Vector2[] vertices = new Vector2[4];
	vertices[0] = new Vector2(x-radius, y+radius);
	vertices[1]= new Vector2(x+radius, y+radius);
	vertices[2]= new Vector2(x-radius, y-radius);
	vertices[3]= new Vector2(x+radius, y-radius);
	octagon.set((Vector2[]) vertices);

	return octagon;
}
 
Example 14
Project: Flappy-Baranus   File: PlayState.java   Source Code and License 6 votes vote down vote up
public PlayState(GameStateManager gsm) {
    super(gsm);
    font = new BitmapFont();
    font.setColor(1.0f, 1.0f, 1.0f, 1.0f);
    bird = new Bird(50, 300);
    camera.setToOrtho(false, FlappyBaran.WIDTH / 2, FlappyBaran.HEIGHT / 2);
    bg = new Texture("backgrnd.jpg");
    ground = new Texture("ground.png");
    groundPos1 = new Vector2(camera.position.x - camera.viewportWidth / 2, GROUND_Y_OFFSET);
    groundPos2 = new Vector2((camera.position.x - camera.viewportWidth / 2) + ground.getWidth(), GROUND_Y_OFFSET);

    tubes = new Array<com.kirdmiv.flappybaranus.sprites.Tube>();

    for (int i = 0; i < TUBE_COUNT; i++){
        tubes.add(new com.kirdmiv.flappybaranus.sprites.Tube(i * (TUBE_SPACING + com.kirdmiv.flappybaranus.sprites.Tube.TUBE_WIDTH)));
    }
}
 
Example 15
Project: cocos2d-java   File: AffineTransform.java   Source Code and License 5 votes vote down vote up
/**Multiply point (x,y,1) by a  affine transform.
 * @return <b>stack object </b>*/
public static final Vector2 PointApplyAffineTransform(final Vector2 point, final AffineTransform t) {
	 Vector2 p = stackVec2;
	 p.x = (t.a * point.x + t.c * point.y + t.tx);
	 p.y = (t.b * point.x + t.d * point.y + t.ty);
	 return p;
 }
 
Example 16
Project: SpaceGame   File: CommandExecutorService.java   Source Code and License 5 votes vote down vote up
/**
 * Execute a given command
 *
 * @param command      - the command to execute
 * @param entitySource - the entities that the command should be run on
 * @param numEntities  - the number of entities
 * @param start        - the first input point (or 0,0)
 * @param end          - the second input point (or 0,0)
 * @param level        - the level that the entities are in
 */
public void executeCommand(Command command, Iterable<Entity> entitySource, int numEntities,
                           Vector2 start, Vector2 end, Level level) {
    //If a command is issued but no entities are around to hear it was the command issued
    if (numEntities == 0) return;
    command.getExecutable().issue(entitySource, numEntities, start, end, level);
    SpaceGame.getInstance()
            .getEventBus()
            .post(commandIssuedEvent.get(entitySource.iterator(), command.getId(), numEntities));
    //If replay is wanted it can be implemented by remembering the times that this was called
}
 
Example 17
Project: GDX-Engine   File: PhysicsTiledScene.java   Source Code and License 5 votes vote down vote up
/**
 * Create mouse joint with ground body, target body and location on target body
 * @param groundBody
 * @param targetBody
 * @param locationWorld
 * @return
 */
public MouseJoint createMouseJoint(Body groundBody, Body targetBody, Vector2 locationWorld){
	MouseJointDef md = new MouseJointDef();
       md.bodyA = groundBody;
       md.bodyB = targetBody;
       md.target.set(locationWorld.x, locationWorld.y);
       md.collideConnected = true;
       md.maxForce = 10000.0f * targetBody.getMass();
       
       MouseJoint _mouseJoint = (MouseJoint)world.createJoint(md);
       targetBody.setAwake(true);
       
       return _mouseJoint;
}
 
Example 18
Project: TH902   File: PlayerReimu.java   Source Code and License 5 votes vote down vote up
@Override
public void Initialize(Entity entity) {
	super.Initialize(entity);
	animationDrawable.setAnimation(animationStay);
	existTime = 0;
	entity.AddComponent(mRenderer = new ImageGroupRenderer(new Drawable[] { animationDrawable, playerAnimation }, 0, null));
	mReimuWing1 = new ReimuWing(new Vector2(transform.position.x, transform.position.y + 20), 4f, mType);
	mReimuWing2 = new ReimuWing(new Vector2(transform.position.x, transform.position.y), -4f, mType);
}
 
Example 19
Project: EarthInvadersGDX   File: GameScreen.java   Source Code and License 5 votes vote down vote up
@Override
public void touchDragged(int screenX, int screenY, int pointer) {
    Vector3 coords = camera.unproject(new Vector3(screenX, screenY, 0));
    boolean left = leftButton.drag(new Vector2(coords.x, coords.y));
    boolean right = rightButton.drag(new Vector2(coords.x, coords.y));
    if (pointers.containsKey(pointer)) {
        int currentValue = pointers.get(pointer);
        pointers.remove(pointer);
        if (left) {
            pointers.put(pointer, 1);
            leftButton.clicked = true;
            rightButton.clicked = false;
        } else if (right) {
            pointers.put(pointer, 2);
            leftButton.clicked = false;
            rightButton.clicked = true;
        } else {
            pointers.put(pointer, 0);
            if (currentValue == 1)
                leftButton.clicked = false;
            else if (currentValue == 2)
                rightButton.clicked = false;
        }
    }
    shopButton.drag(new Vector2(coords.x, coords.y));
    if (health <= 0) {
        retry.drag(new Vector2(coords.x, coords.y));
        exit.drag(new Vector2(coords.x, coords.y));
    }
    if (paused) {
        pauseExit.drag(new Vector2(coords.x, coords.y));
        resume.drag(new Vector2(coords.x, coords.y));
        music.drag(new Vector2(coords.x, coords.y));
    }
}
 
Example 20
Project: cocos2d-java   File: GLView.java   Source Code and License 5 votes vote down vote up
/**
 * Get the visible origin point of opengl viewport.
 */
public Vector2 getVisibleOrigin() {
	if (_resolutionPolicy == ResolutionPolicy.NO_BORDER) {
        return visibleOrigin.set((_designResolutionSize.width - _screenSize.width/_scaleX)/2, 
                           (_designResolutionSize.height - _screenSize.height/_scaleY)/2);
    } else {
        return visibleOrigin.setZero();
    }
}
 
Example 21
Project: arcadelegends-gg   File: LevelScreen.java   Source Code and License 5 votes vote down vote up
private int spawnPlayer() {
    playerEnt = arcadeWorld.spawnPlayer();
    playerHelper = new PlayerHelper(playerEnt, arcadeWorld, levelAssets);
    Vector2 pos = arcadeWorld.getSpawnPosition();
    camera.position.set(pos.x, pos.y - 9, camera.position.z);
    return playerEnt;
}
 
Example 22
Project: water2d-libgdx   File: IntersectionUtils.java   Source Code and License 5 votes vote down vote up
private static Vector2 fromPolar(float angle, float magnitude) {
	Vector2 res = new Vector2((float) Math.cos(angle), (float) Math.sin(angle));
	res.x = res.x * magnitude;
	res.y = res.y * magnitude;

	return res;
}
 
Example 23
Project: school-game   File: TutorialDummy.java   Source Code and License 5 votes vote down vote up
@Override
public void render(Batch batch, float deltaTime)
{
    if (body == null) return;

    Color oldColor = batch.getColor();

    batch.setColor(1f, (health + 5)/10f, (health + 5)/10f, 1f);

    Vector2 pos = body.getPosition();
    pos.scl(Physics.PPM);

    TextureRegion region = MathUtils.isZero(hitTimer) ? dummy : dummy_hit;

    batch.draw(region,                                    // TextureRegion (front, back, side)
            pos.x - dummy.getRegionWidth() / 2,           // Offset to the X position (character center)
            pos.y,                                        // Y position is at the foots
            dummy.getRegionWidth() / 2,                   // Origin X (important for flipping)
            dummy.getRegionHeight(),                      // Origin Y
            dummy.getRegionWidth(),                       // Width
            dummy.getRegionHeight(),                      // Height
            1f,                                           // Scale X (-1 to flip)
            1f,                                           // Scale Y
            0f);                                          // Rotation

    batch.setColor(oldColor);
}
 
Example 24
Project: cocos2d-java   File: CollideAlgorithms.java   Source Code and License 5 votes vote down vote up
/**测试在Axis轴上的A、B是否分离
 * 用于MTD测试的方法
 * <br>true为分离
 * @param Axis
 * @param A
 * @param B
 * @return */
public static final boolean axisSeparatePolygons(final Vector2 Axis, final Polygon A, final AABBShape B,
		final Vector2 positionA, final Vector2 positionB) {
	pair = CalculateInterval(Axis, A, positionA);
	final float mina = pair.min;
	final float maxa = pair.max;
	
	pair = CalculateInterval(Axis, B, positionB);
	final float minb = pair.min;
	final float maxb = pair.max;
	
	if (mina > maxb || minb > maxa) 
		return true; 
	return false; 
}
 
Example 25
Project: SpaceChaos   File: Segment.java   Source Code and License 5 votes vote down vote up
public Range projectSegment(Vector2 onto) {
    // create new range or use an recycled range
    Range range = RangePool.create();

    // normailize vector
    onto.nor();

    // calculate min and max value with dot product
    float min = onto.dot(point1);
    float max = onto.dot(point2);
    range.set(min, max);

    return range;
}
 
Example 26
Project: SpaceChaos   File: FastMath.java   Source Code and License 5 votes vote down vote up
public static boolean checkVectorsParallel(Vector2 v1, Vector2 v2) {
    // rotate vector 90 degrees
    Vector2 rotatedVector1 = rotateVector90(v1, Vector2Pool.create());

    // 2 vectors are parallel, if dot product = 0
    float dotProduct = rotatedVector1.dot(v2);

    Vector2Pool.free(rotatedVector1);

    return dotProduct == 0;
}
 
Example 27
Project: cocos2d-java   File: DrawNode.java   Source Code and License 5 votes vote down vote up
/** draw a triangle with color. 
 *
 * @param p1 The triangle vertex point.
 * @param p2 The triangle vertex point.
 * @param p3 The triangle vertex point.
 * @param color The triangle color.
 */
public void drawTriangle( Vector2 p1,  Vector2 p2,  Vector2 p3,  Color color) {
	if(!batchCommand) {	
		clear();
	}
	pushShapeCommandCell(DrawType.Triange, color, ShapeType.Line,
			lineWidth, MessUtils.pointsToFloats(p1, p2, p3));
}
 
Example 28
Project: SpaceGame   File: SelectionSystem.java   Source Code and License 5 votes vote down vote up
@Override
public boolean touchDown(int screenX, int screenY, int pointer, int button) {
    if (checkProcessing() && button == Buttons.LEFT) {
        Vector3 vec = camera.unproject(new Vector3(Gdx.input.getX(), Gdx.input.getY(), 0));
        selectionBegin = new Vector2(vec.x, vec.y);
        return true;
    }
    return false;
}
 
Example 29
Project: enklave   File: TutorialDialog.java   Source Code and License 5 votes vote down vote up
public Group createPuls(float x, float y){
    grPuls = new Group();
    Texture txt = managerAssets.getAssetsTutorial().getTexture(NameFiles.circlePulsTutorial);
    Image image = new Image(new TextureRegion(txt));
    Vector2 crop = Scaling.fit.apply(txt.getWidth(),txt.getHeight(),WIDTH,HEIGHT);
    image.setSize(crop.x * 0.135f, crop.y * 0.135f);
    image.setPosition(x, y);
    grPuls.addActor(image);
    txt = managerAssets.getAssetsTutorial().getTexture(NameFiles.PulsCircleScalable);
    Image puls = new Image(new TextureRegion(txt));
    crop = Scaling.fit.apply(txt.getWidth(),txt.getHeight(),WIDTH,HEIGHT);
    puls.setPosition(image.getRight() - image.getWidth() / 2, image.getTop() - image.getHeight() / 2);
    puls.setSize(1, 1);
    MoveToAction move = new MoveToAction();
    move.setDuration(1);
    move.setPosition(image.getRight() - image.getWidth() / 2 - crop.x*0.085f, image.getTop() - image.getHeight() / 2 - crop.y*0.085f);
    MoveToAction mo = new MoveToAction();
    mo.setDuration(0);
    mo.setPosition(image.getRight() - image.getWidth() / 2, image.getTop() - image.getHeight() / 2);
    ScaleToAction scale = new ScaleToAction();
    scale.setScale(WIDTH*0.17f);
    scale.setDuration(1);
    ScaleToAction sc = new ScaleToAction();
    sc.setDuration(0);
    sc.setScale(0);
    RepeatAction repeat = new RepeatAction();
    repeat.setCount(RepeatAction.FOREVER);
    repeat.setAction(new SequenceAction(scale, sc));
    puls.addAction(repeat);
    RepeatAction r = new RepeatAction();
    r.setCount(RepeatAction.FOREVER);
    r.setAction(new SequenceAction(move, mo));
    puls.addAction(r);
    grPuls.addActor(puls);
    return grPuls;
}
 
Example 30
Project: cocos2d-java   File: ShapeAlgorithms.java   Source Code and License 5 votes vote down vote up
/**求点p到线段ab所处直线的最短平方距离
	 * <br><b>use: pool1 pool2</b>
	 * @param p 测试点
	 * @param a 线段起始点
	 * @param b 线段终点
	 * @return 最短平方距离 */
	public static final float ClosetDistanceSquarePtSegment(final Vector2 p,final Vector2 a,final Vector2 b){
//		Vector2 ab=b.sub(a);
		pool1.set(b.x-a.x, b.y-a.y);
		pool1.nor();
		pool2.set(p.x-a.x, p.y-a.y);
//		return Math.abs(Vector2.cross(p.sub(a), pool1));
		return MathUtils.abs(V2.cross(pool2, pool1));
	}
 
Example 31
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 32
Project: libgdx_ui_editor   File: MainWindow.java   Source Code and License 5 votes vote down vote up
@Override
public void align(AlignEvent alignEvent) {
    if (selectedGroup.getAllActor().size > 1) {
        Actor tmp = selectedGroup.getAllActor().first();
        Vector2 tmpVec = new Vector2();
        tmp.localToStageCoordinates(tmpVec);
        for (Actor actor : selectedGroup.getAllActor()) {
            if (actor.equals(tmp)) continue;
            Vector2 vector2 = new Vector2(tmpVec);
            actor.getParent().stageToLocalCoordinates(vector2);
            switch (alignEvent.align) {
                case Align.left:
                    actor.setPosition(vector2.x, actor.getY());
                    break;
                case Align.right:
                    actor.setPosition(vector2.x + tmp.getWidth(), actor.getY() + actor.getHeight() / 2, Align.right);
                    break;
                case Align.center:
                    actor.setPosition(vector2.x + tmp.getWidth() / 2, actor.getY(Align.center), Align.center);
                    break;
                case Config.centerH:
                    actor.setPosition(actor.getX(Align.center), vector2.y + tmp.getHeight() / 2, Align.center);
                    break;
                case Align.bottom:
                    actor.setPosition(actor.getX(), vector2.y);
                    break;
                case Align.top:
                    actor.setPosition(actor.getX(), vector2.y + tmp.getHeight(), Align.topLeft);
                    break;
            }
        }
    }
}
 
Example 33
Project: cocos2d-java   File: DrawNode.java   Source Code and License 5 votes vote down vote up
public void drawSolidTriangle( Vector2 p1,  Vector2 p2,  Vector2 p3,  Color color) {
	if(!batchCommand) {	
		clear();
	}
	pushShapeCommandCell(DrawType.Triange, color, ShapeType.Line,
			lineWidth, MessUtils.pointsToFloats(p1, p2, p3));
}
 
Example 34
Project: Race99   File: GameObjectFactory.java   Source Code and License 5 votes vote down vote up
public static GameObject createGameObjectWithBox2DBody(Vector2 gameObjectPos, Texture texture, Vector3 densityFrictionRestitution,
                                   BodyDef.BodyType bodyType, Shape.Type shapeType,
                                   World world) {
    GameObject gameObject = new GameObject();
    gameObject.setPosition(gameObjectPos.x, gameObjectPos.y);
    gameObject.setTexture(texture);
    gameObject.setSprite(new Sprite(texture));
    gameObject.getSprite().setOriginCenter();
    gameObject.setWorld(world);
    BodyCreator bodyCreator = new BodyCreator();
    gameObject.setBody(bodyCreator.createBody(new Vector2(gameObject.getX(), gameObject.getY()), texture, bodyType, world, shapeType, densityFrictionRestitution));
    bodyCreator = null;
    return gameObject;
}
 
Example 35
Project: TH902   File: BaseProjectile.java   Source Code and License 5 votes vote down vote up
public static Entity Create(Vector2 position, BulletType formcircles, BulletType colorred, Component... Ves){
	Entity entity = Entity.Create();
	entity.AddComponent(new Transform(position));
	entity.AddComponent(new ImageRenderer(ResourceManager.barrages.get(bulletTypeArray[formcircles.getType()][colorred.getType()]), 0));
	entity.AddComponent(new BaseProjectile(formcircles.getType()));
	for (Component tmpc : Ves) {  
          entity.AddComponent(tmpc);
       }
	return entity;
}
 
Example 36
Project: Klooni1010   File: Piece.java   Source Code and License 5 votes vote down vote up
private Piece(int lSize, int rotateCount, int colorIndex) {
    this.colorIndex = colorIndex;

    pos = new Vector2();
    cellCols = cellRows = lSize;
    shape = new boolean[lSize][lSize];

    rotation = rotateCount % 4;
    switch (rotation) {
        case 0: // ┌
            for (int j = 0; j < lSize; ++j)
                shape[0][j] = true;
            for (int i = 0; i < lSize; ++i)
                shape[i][0] = true;
            break;
        case 1: // ┐
            for (int j = 0; j < lSize; ++j)
                shape[0][j] = true;
            for (int i = 0; i < lSize; ++i)
                shape[i][lSize-1] = true;
            break;
        case 2: // ┘
            for (int j = 0; j < lSize; ++j)
                shape[lSize-1][j] = true;
            for (int i = 0; i < lSize; ++i)
                shape[i][lSize-1] = true;
            break;
        case 3: // └
            for (int j = 0; j < lSize; ++j)
                shape[lSize-1][j] = true;
            for (int i = 0; i < lSize; ++i)
                shape[i][0] = true;
            break;
    }
}
 
Example 37
Project: SpaceGame   File: PositionComponent.java   Source Code and License 5 votes vote down vote up
/**
 * Set this component's coordinates from those of a given vector
 *
 * @param v - the vector to use
 */
public void setFrom(Vector2 v) {
    if (v.x == this.x && v.y == this.y) return;
    x = v.x;
    y = v.y;
    setDirty();
}
 
Example 38
Project: cocos2d-java   File: Polygon.java   Source Code and License 5 votes vote down vote up
public void rotate270() {
	for(Vector2 v:points){
		v.set(v.y, -v.x);  
	}
	computeShapeAABB();
	computeShapeCenter();
}
 
Example 39
Project: cocos2d-java   File: Contact.java   Source Code and License 5 votes vote down vote up
/**检测两个多边形相交并计算MTD
 * @param o1
 * @param o2 */
private final void PlaygonTestPolygonMTD(final Shape s1,final Shape s2, 
		final Vector2 positionA, final Vector2 positionB){
	if(Intersect((Polygon)s1, (Polygon)s2, positionA, positionB, MTD)){
		contacting = true;
		handleResult();
	}
}
 
Example 40
Project: GangsterSquirrel   File: Player.java   Source Code and License 5 votes vote down vote up
/**
 * Create the shape of the player, which is half the width of the player texture because it is larger to include weapons
 * @return the shape
 */
private PolygonShape getPlayerShape() {

    PolygonShape shape = new PolygonShape();
    shape.setAsBox(
            PLAYER_PIXEL_WIDTH / 4 / MainGameClass.PPM, // half the texture width to not include white space of the texture in the collision box
            PLAYER_PIXEL_HEIGHT / 2 / MainGameClass.PPM, // the full texture height (sizes are half sizes, so divided by two)
            new Vector2( - PLAYER_PIXEL_WIDTH / 4 / MainGameClass.PPM, 0), // center of the box, needs to be half of the half size of the texture negative to make the flipping work
            0f // the angle of the box
    );

    return shape;
}