List of usage examples for com.badlogic.gdx.math Vector2 scl
@Override
public Vector2 scl(Vector2 v)
From source file:de.cubicvoxel.openspacebox.ingame.object.Ship.java
License:Open Source License
private void moveTowards(Vector2 direction, float delta) { Vector2 movement = new Vector2(direction); movement.scl(shipType.getPhysics().getAcceleration() * delta); Vector2 totalVelocity = new Vector2(velocity).add(movement); totalVelocity.limit(getMaxSpeed());/* w w w . j a va 2 s. c o m*/ velocity = totalVelocity; }
From source file:de.r2soft.r2physics.instances.OrbitalBody.java
License:Open Source License
private void applyForce(OrthographicCamera camera) { R2Float AccDT = new R2Float(acceleration.x, acceleration.y); AccDT.scl(Gdx.graphics.getDeltaTime()); // todo get delta t velocity.add(AccDT);// w w w . j a v a 2 s .c o m R2Float VelDT = new R2Float(velocity.x, velocity.y); VelDT.scl(Gdx.graphics.getDeltaTime()); // todo get delta t position.add(VelDT); /** Draws debug vector. Remove this from build version */ R2Float tmp = parent.getPosition().cpy(); renderer.setProjectionMatrix(camera.combined); renderer.begin(ShapeType.Line); renderer.setColor(1, 1, 1, 1); Vector2 tmp2 = new Vector2(acceleration.x, acceleration.y); tmp2.scl(10f); tmp2.add(tmp.x, tmp.y); renderer.line(new Vector2(tmp.x, tmp.y), tmp2); renderer.end(); parent.updatePosition(position); }
From source file:edu.lehigh.cse.lol.Obstacle.java
License:Open Source License
/** * Call this on an Obstacle to make it into a pad that changes the hero's * speed when the hero glides over it./*from w w w . java 2 s.com*/ * * These "pads" will multiply the hero's speed by the factor given as a * parameter. Factors can be negative to cause a reverse direction, less * than 1 to cause a slowdown (friction pads), or greater than 1 to serve as * zoom pads. * * @param factor Value to multiply the hero's velocity when it collides with * this Obstacle */ public void setPad(final float factor) { // disable collisions on this obstacle setCollisionsEnabled(false); // register a callback to multiply the hero's speed by factor mHeroCollision = new CollisionCallback() { @Override public void go(Actor h, Contact c) { Vector2 v = h.mBody.getLinearVelocity(); v.scl(factor); h.updateVelocity(v.x, v.y); } }; }
From source file:EntityManager.ScreenControlsSystem.java
@Override public void update(float delta) { // System.out.println("Controls update. entities found:" + entities.size()); for (int i = 0; i < players.size(); i++) { Entity e = players.get(i); playerDirection = (float) Math.toDegrees(bm.get(e).body.getAngle()); BodyComponent body = bm.get(e);//w w w . ja va 2 s. c o m cameraLoc = body.body.getWorldCenter().cpy(); float angleR = body.body.getAngle(); Vector2 look = new Vector2((float) Math.cos(angleR), (float) Math.sin(angleR)); look.scl(3); cameraLoc.add(look); playerLoc = body.body.getWorldCenter().cpy(); // playerLoc.add(body.body.getAngle()) // FlashlightComponent flashlight = fm.get(e); // flashlight.flashlight.setDirection((float) Math.toDegrees(body.body.getAngle())); // flashlight.flashlight.setPosition(body.body.getWorldCenter()); if (touchpad.isTouched()) { Vector2 vel = new Vector2(touchpad.getKnobPercentX() * 400, touchpad.getKnobPercentY() * 400); // body.body.applyLinearForce(playerLoc, vel, true); body.body.applyForceToCenter(vel, true); // body.body.applyForceToCenter(touchpad.getKnobPercentX()*4, touchpad.getKnobPercentY()*4,true); // System.out.println("touched"); } // flashlight.flashlight.setDirection(body.body.getAngle()); if (touchpadRight.isTouched()) { double angle = Math.atan2(touchpadRight.getKnobPercentY(), touchpadRight.getKnobPercentX()); body.body.setTransform(playerLoc.x, playerLoc.y, (float) angle); } if (button1press) { button.setChecked(false); if (collisionM.has(e)) { for (Entity door : doors) if (collisionM.has(door) && playersC.get(players.first()).grab == null) { // door.getComponent(JointComponent.class).toggleLock(); If we want to lock the door; RopeJointDef grab = new RopeJointDef(); grab.bodyA = bm.get(door).body; grab.localAnchorA.set(collisionM.get(e).manifold.getPoints()[1].x, collisionM.get(e).manifold.getPoints()[1].y); grab.localAnchorB.set(collisionM.get(door).manifold.getPoints()[1].x, collisionM.get(e).manifold.getPoints()[1].y); grab.bodyB = bm.get(players.first()).body; grab.maxLength = 50 / PPM; grab.collideConnected = true; playersC.get(players.first()).grab(world.createJoint(grab)); } } } else { if (playersC.get(e).grab != null) { world.destroyJoint(playersC.get(e).grab); playersC.get(e).endGrab(); System.out.println("button release"); } } if (button2press) { button.setChecked(false); EntityManager .add(new Entity().add(new BodyComponent(Bullet.getBullet(bm.get(players.first()).body))) .add(new BulletComponent())); } } }
From source file:es.eucm.ead.editor.view.widgets.groupeditor.Handles.java
License:Open Source License
/** * Updates the handles scale to keep them at the same stage-relative size *//*from w w w . jav a2 s . c o m*/ public void updateHandlesScale() { for (Handle handle : handles) { handle.stageToLocalCoordinates(tmp2.set(0, 0)); if (handle instanceof OriginHandle || handle instanceof RotationHandle) { handle.stageToLocalCoordinates(tmp3.set(handleCircleSize, handleCircleSize)); } else { handle.stageToLocalCoordinates(tmp3.set(handleSquareSize, handleSquareSize)); } tmp3.sub(tmp2); handle.setRadius(tmp3.len()); } // Set rotation handle Vector2 o = localToStageCoordinates(tmp1.set(handles[0].getX(), handles[0].getY())); Vector2 n = localToStageCoordinates(tmp2.set(handles[6].getX(), handles[6].getY())).sub(o).nor(); Vector2 top = localToStageCoordinates(tmp3.set(handles[7].getX(), handles[7].getY())); top.add(n.scl(rotationHandleOffset)); stageToLocalCoordinates(top); handles[ROTATION_HANDLE_INDEX].setX(top.x); handles[ROTATION_HANDLE_INDEX].setY(top.y); }
From source file:es.eucm.ead.engine.collision.BoundingAreaBuilder.java
License:Open Source License
/** * Creates a minimum circle that contains the given entity. The algorithm * takes into account renderers' colliders (if available) and children. The * algorithm uses {@link #getBoundingPolygon(EngineEntity, Group, Group)} * and then calculates radius and center by finding the pair of vertex with * longest distance./* w w w .j av a 2 s . com*/ * * @param entity * The entity to build a bounding circle for. * @return The bounding circle, in coordinates of the * {@link Layer#SCENE_CONTENT} layer. May return {@code null} if * this entity is not a descendant of {@link Layer#SCENE_CONTENT}. */ public static CircleWrapper getBoundingCircle(EngineEntity entity) { Polygon pol = getBoundingPolygon(entity); // Calculate pair of vertex with longest distance Vector2 center = Pools.obtain(Vector2.class); float maxDistance = Float.NEGATIVE_INFINITY; for (int i = 0; i < pol.getVertices().length; i += 2) { Vector2 vertex1 = Pools.obtain(Vector2.class); Vector2 vertex2 = Pools.obtain(Vector2.class); Vector2 vertex2toVertex1 = Pools.obtain(Vector2.class); vertex1.set(pol.getVertices()[i], pol.getVertices()[i + 1]); for (int j = 0; j < pol.getVertices().length - 1; j += 2) { if (i == j) { continue; } vertex2.set(pol.getVertices()[j], pol.getVertices()[j + 1]); vertex2toVertex1.set(vertex1); float distance = vertex2toVertex1.sub(vertex2).len(); if (distance > maxDistance) { maxDistance = distance; center.set(vertex2).add(vertex2toVertex1.scl(0.5f)); } } Pools.free(vertex1); Pools.free(vertex2); Pools.free(vertex2toVertex1); } Circle circle = Pools.obtain(Circle.class); circle.set(center.x, center.y, maxDistance / 2.0F); Pools.free(center); CircleWrapper circleWrapper = Pools.obtain(CircleWrapper.class); circleWrapper.set(circle); return circleWrapper; }
From source file:es.eucm.ead.engine.collision.CircleWrapper.java
License:Open Source License
@Override protected boolean intersectToSegment(Vector2 start, Vector2 end, Vector2 intersection) { Vector2 v = Pools.obtain(Vector2.class); if (circle.contains(start) && !circle.contains(end)) { v.set(end);//from w ww. j a va 2 s . co m v.sub(start); } else if (!circle.contains(start) && circle.contains(end)) { v.set(start); v.sub(end); } else { return false; } v.scl(circle.radius / v.len()); getCenter(intersection); intersection.add(v); Pools.free(v); return true; }
From source file:headmade.arttag.Guard.java
License:Apache License
public void update(ArtTagScreen artTag, float delta) { if (body == null) { return;// w ww. j av a 2s .co m } isRunning = isAlert || isCautious; moveSpeed = isRunning ? maxMoveSpeed * runFactor : isSuspicious ? maxMoveSpeed * 0.75f : isHeardPlayer ? 0.5f : maxMoveSpeed; final Vector2 oldMoveVec = targetMoveVec.cpy(); Vector2 targetPoint = null; Float distanceToPlayer = null; if (isLightOn) { for (final Fixture fixture : playerInView) { targetPoint = fixture.getBody().getWorldCenter().cpy(); final Vector2 diffVec = body.getWorldCenter().cpy().sub(targetPoint); boolean seesPlayer = false; distanceToPlayer = diffVec.len(); if (distanceToPlayer < 1f) { seesPlayer = true; } else { final Vector2 outOfBodyVec = diffVec.scl(fixture.getShape().getRadius() * 1.01f); targetPoint.add(outOfBodyVec); seesPlayer = light.contains(targetPoint.x, targetPoint.y); } // Gdx.app.log(TAG, light.contains(targetPoint.x, targetPoint.y) + " diffVec.length " + diffVec.len()); if (seesPlayer) { // Gdx.app.log(TAG, "Guard sees player"); playerLastSeenVec = fixture.getBody().getWorldCenter().cpy(); if (!isAlert) { Assets.instance.playSound(AssetSounds.whosThere); } isAlert = true; Player.instance.isSpotted = true; reactionTime = 0f; } else { if (isAlert) { Assets.instance.playSound(AssetSounds.huh); reactionTime = MAX_REACTION_TIME; isCautious = true; } isAlert = false; } } } // handle hearing if (Player.instance.isRunning && (Player.instance.isMoveDown || Player.instance.isMoveUp || Player.instance.isMoveLeft || Player.instance.isMoveRight) && null != Player.instance.body) { if (distanceToPlayer == null) { distanceToPlayer = body.getWorldCenter().cpy().sub(Player.instance.body.getWorldCenter()).len(); } if (distanceToPlayer < MAX_LIGHT_CONE_LENGTH * 0.9f) { sumDeltaSinceHeardPlayer = 0; final RayCastCallback callback = new RayCastCallback() { @Override public float reportRayFixture(Fixture fixture, Vector2 point, Vector2 normal, float fraction) { // Gdx.app.log(TAG, "reportRayFixture " + point + " normal " + normal); if (fixture.isSensor()) { // Gdx.app.log(TAG, "Raycast ignoring sensor"); return 1; } if (body.equals(fixture.getBody())) { // this is the guards body so there is nothing inbetween them // Gdx.app.log(TAG, "Guard CAN see the point where the noise happened" + Player.instance.body.getWorldCenter()); // playerLastHeardVisibleVec = Player.instance.body.getWorldCenter().cpy(); return 1; } // Gdx.app.log(TAG, "Fall through"); isHearingObstructed = true; return 0; } }; try { isSuspicious = true; playerLastHeardVec = Player.instance.body.getWorldCenter().cpy(); isHearingObstructed = false; // Gdx.app.log(TAG, "###################################"); // Gdx.app.log(TAG, "Guard " + body.getWorldCenter()); // Gdx.app.log(TAG, "Player " + playerLastHeardVec); artTag.world.rayCast(callback, playerLastHeardVec, body.getWorldCenter()); if (!isHearingObstructed) { playerLastHeardVisibleVec = Player.instance.body.getWorldCenter().cpy(); } } catch (final Exception e) { Gdx.app.error(TAG, "Error Raycasting :(", e); } } else { sumDeltaSinceHeardPlayer += delta; } } else { sumDeltaSinceHeardPlayer += delta; } isHeardPlayer = playerLastHeardVisibleVec != null || sumDeltaSinceHeardPlayer < 3; if (isTouchingPlayerLightCone && Player.instance.isLightOn) { // isAlert = true; } // handle backToPath if (isAlert || isCautious || (isSuspicious && playerLastHeardVisibleVec != null)) { if (lastVisibleVecBackToPath == null) { lastVisibleVecBackToPath = body.getWorldCenter(); } Vector2 checkPoint = path.get(currentPathIndex); if (backToPath.size > 0) { checkPoint = backToPath.get(backToPath.size - 1); } if (BODY_RADIUS < checkPoint.dst(body.getWorldCenter())) { // not touching checkpoint // Gdx.app.log(TAG, "Goard not touching checkpoint"); final RayCastCallback callback = new RayCastCallback() { @Override public float reportRayFixture(Fixture fixture, Vector2 point, Vector2 normal, float fraction) { // Gdx.app.log(TAG, "reportRayFixture adds new backToPathPoint" + lastVisibleVecBackToPath); backToPath.add(lastVisibleVecBackToPath.cpy()); return 0; } }; try { artTag.world.rayCast(callback, body.getWorldCenter(), checkPoint); } catch (final Exception e) { Gdx.app.error(TAG, "Error Raycasting :(", e); } } lastVisibleVecBackToPath = body.getWorldCenter(); } // determine targetPoint if (isAlert && playerInView.size > 0 && Player.instance.body != null) { targetPoint = Player.instance.body.getWorldCenter(); } else if (isCautious && playerLastSeenVec != null) { targetPoint = playerLastSeenVec; if (BODY_RADIUS / 10 > targetPoint.dst2(body.getPosition())) { // Lost player Assets.instance.playSound(AssetSounds.hm); Gdx.app.log(TAG, "Guard no longer cautious"); isCautious = false; isSuspicious = true; } } else if (isSuspicious && playerLastHeardVisibleVec != null) { targetPoint = playerLastHeardVisibleVec; // Gdx.app.log(TAG, "Guard going to playerLastHeardVisibleVec"); if (BODY_RADIUS / 10 > targetPoint.dst2(body.getPosition())) { // Lost player Assets.instance.playSound(AssetSounds.hm); Gdx.app.log(TAG, "Guard no longer suspicious"); isSuspicious = false; playerLastHeardVisibleVec = null; } } else { lastVisibleVecBackToPath = null; if (backToPath.size > 0) { // following Path back to path targetPoint = backToPath.get(backToPath.size - 1); if (BODY_RADIUS / 10 > targetPoint.dst(body.getPosition())) { // Gdx.app.log(TAG, "Guard reached target back to path point " + targetPoint); backToPath.pop(); } } else { // following path isSuspicious = false; targetPoint = path.get(currentPathIndex); if (BODY_RADIUS > targetPoint.dst(body.getPosition())) { // Gdx.app.log(TAG, "Guard reached target point " + targetPoint); currentPathIndex++; if (currentPathIndex >= path.size) { currentPathIndex = 0; } targetPoint = path.get(currentPathIndex); // Gdx.app.log(TAG, "New target point " + targetPoint); } } } targetMoveVec = targetPoint.cpy().sub(body.getPosition()); targetMoveVec.nor().scl(moveSpeed); if (MathUtils.isEqual(0f, oldMoveVec.angle(targetMoveVec))) { sumDeltaSinceMoveChange += delta; } else { // movment direction changed sumDeltaSinceMoveChange = 0f; } final float alpha = reactionTime > 0 ? MathUtils.clamp(sumDeltaSinceMoveChange / reactionTime, 0.1f, 1f) : 1f; body.setLinearVelocity(targetMoveVec); final Vector2 bodyRotVec = new Vector2(1f, 0f); bodyRotVec.setAngleRad(body.getAngle()); float angleDiff; if (!isAlert && !isSuspicious && isHeardPlayer && null == playerLastHeardVisibleVec && null != playerLastHeardVec) { // look at last heard angleDiff = bodyRotVec.angleRad(playerLastHeardVec.cpy().sub(body.getWorldCenter()).rotate90(-1)); } else { angleDiff = bodyRotVec.angleRad(targetMoveVec.cpy().rotate90(-1)); } final float rotByRad = MathUtils.clamp(angleDiff, -(MAX_ROTATION_SPEED * delta) / reactionTime, MAX_ROTATION_SPEED * delta / reactionTime); // Gdx.app.log(TAG, "angleDiff: " + angleDiff + " rotByRad: " + rotByRad + " bodyRotVec: " + bodyRotVec + " - targetMoveVec: // " // + targetMoveVec); // is moving? if (!MathUtils.isEqual(targetMoveVec.len2(), 0f)) { if (Player.instance.body != null) { final float dist = body.getPosition().dst(Player.instance.body.getPosition()); float volume = isRunning ? STEP_VOLUME * 2 : STEP_VOLUME; if (dist > 1) { volume = volume / dist; } sound.setVolume(stepSoundId, volume); sound.setPitch(stepSoundId, isRunning ? runFactor : 1f); body.setTransform(body.getPosition(), body.getAngle() + rotByRad); } } else { sound.setVolume(stepSoundId, 0f); sound.setPitch(stepSoundId, 1f); } light.setActive(isLightOn); }
From source file:MeshBoneUtil.MeshRenderRegion.java
License:Open Source License
public void runUvWarp() { int cur_uvs_index = getUVsIndex(); for (int i = 0; i < uv_warp_ref_uvs.size(); i++) { Vector2 set_uv = uv_warp_ref_uvs.get(i).cpy(); set_uv.sub(uv_warp_local_offset); set_uv.scl(uv_warp_scale); set_uv.add(uv_warp_global_offset); /*/* w w w . j a v a2 s .c o m*/ set_uv -= uv_warp_local_offset; set_uv *= uv_warp_scale; set_uv += uv_warp_global_offset; */ store_uvs[0 + cur_uvs_index] = set_uv.x; store_uvs[1 + cur_uvs_index] = set_uv.y; /* store_uvs[0 + cur_uvs_index] = (float)set_uv.X; store_uvs[1 + cur_uvs_index] = (float)set_uv.Y; */ cur_uvs_index += 2; } }
From source file:org.ams.prettypaint.OutlinePolygon.java
License:Open Source License
@Override public Array<Vector2> getVerticesRotatedScaledAndTranslated(float rotation, float scale, float transX, float transY) { for (int i = 0; i < vertices.size; i++) { Vector2 w = verticesRotatedAndTranslated.items[i]; w.set(vertices.items[i]);//w w w . j a v a2s . c o m w.rotateRad(rotation); w.scl(scale); w.add(transX, transY); } return verticesRotatedAndTranslated; }