List of usage examples for com.badlogic.gdx.math Vector2 dst2
@Override public float dst2(Vector2 v)
From source file:com.agateau.pixelwheels.map.WaypointStore.java
License:Open Source License
public OrientedPoint getValidPosition(Vector2 pos, float lapDistance) { int nextIdx = getWaypointIndex(lapDistance); int prevIdx = getPreviousIndex(nextIdx); Vector2 prev = mWaypointInfos.get(prevIdx).waypoint; Vector2 next = mWaypointInfos.get(nextIdx).waypoint; Vector2 projected = AgcMathUtils.project(pos, prev, next); float waypointSquareLength = prev.dst2(next); if (projected.dst2(prev) > waypointSquareLength) { // projected is after the [prev, next] segment projected.set(next);//from www .j av a 2s . c o m } else if (projected.dst2(next) > waypointSquareLength) { // projected is before the [prev, next] segment projected.set(prev); } tmpPoint.x = projected.x; tmpPoint.y = projected.y; tmpPoint.angle = AgcMathUtils.normalizeAngle(AgcMathUtils.segmentAngle(prev, next)); return tmpPoint; }
From source file:com.jmolina.orb.elements.LinearMagnetic.java
License:Open Source License
/** * Indica si un punto se encuentra en "rango cercano" del elemento. "Rango cercano" es la distancia entre * el centro del elemento y el pico ms alejado del campo magntico. Cualquier punto ms alejado * no se ver afectado por el campo. Se usa para evitar el clculo de fuerza en los elementos * que no estn suficientemente cerca del punto. * * Compara las distancias al cuadrado para evitar el clculo de las races cuadradas. Esta funcin * acta de primera discriminante para calcular la fuerza ejercida sobre el punto. * * @param point Un punto en coordenadas del mundo * @return/*ww w .ja va 2 s .c om*/ */ private boolean closeRange(Vector2 point) { float maximumFieldDistance2 = 0.25f * getWidth() * getWidth() + getThreshold() * getThreshold(); float pointCenterDistance2 = point.dst2(getPosition()); return pointCenterDistance2 <= maximumFieldDistance2; }
From source file:com.jmolina.orb.elements.RadialMagnetic.java
License:Open Source License
/** * Indica si un punto se encuentra dentro del campo de accin. * * Compara distancias al cuadrado para evitar el clculo de races cuadradas. Esta funcin * acta de primera discriminante para calcular la fuerza ejercida sobre el punto. * * @param point Punto en unidades del mundo * @return/* w w w.j av a 2s . co m*/ */ private boolean belowThreshold(Vector2 point) { return point.dst2(getPosition()) <= getThreshold() * getThreshold(); }
From source file:com.t0ast.parkour.training.ParkourFitnessRater.java
private float getDistanceToNearestCheckpoint(Vector2[] checkpoints, Vector2 position) { float smallestDist = Float.MAX_VALUE; for (Vector2 checkpoint : checkpoints) { float dist = position.dst2(checkpoint); if (dist < smallestDist) smallestDist = dist;/*from w ww . j av a2 s . co m*/ } return (float) Math.sqrt(smallestDist); }
From source file:es.eucm.ead.engine.paths.PathFinder.java
License:Open Source License
/** * Finds shortcut-endpoints (or direct hits if 'recursive' is set to false) * between a source-to-target segment and the current polygon. * /*from w w w. j av a2 s. c o m*/ * @param source * of the current segment * @param target * of the current segment * @param recursive * if the intersection point itself is not desired; instead, the * intersections of the polygon and the endpoints of the * intersected segment (1 level of recursion) will be returned. * @return an array of points: * <ul> * <li>If 1 result is returned, then the segment does not cross the * polygon, and lies entirely within; or "recursive" was set to * false, and the first intersection of source-to-target is directly * returned.</li> * <li> * If more results are returned, then "recursive" was set to true, * and the results will contain the points returned by calling this * method recursively (with "recursive" set to false) for each * intersection.</li> * </ul> */ Vector2[] lineEndpoints(Vector2 source, Vector2 target, boolean recursive) { Vector2 moreThanEpsilon = new Vector2(target).sub(source).nor().scl(MINIMAL_DISPLACEMENT); Vector2 justAfterSource = new Vector2(source).add(moreThanEpsilon); boolean startsByGoingOutside = !pathBoundary.contains(justAfterSource.x, justAfterSource.y); if (!startsByGoingOutside) { Vector2 justBeforeTarget = new Vector2(target).sub(moreThanEpsilon).sub(moreThanEpsilon); if (!PathUtils.intersectSegmentPolygon(justAfterSource, justBeforeTarget, pathBoundary, new Vector2())) { return new Vector2[] { target }; } else { } } else { // starts by going outside: source on segment, return endpoints for (int i = 0; i < boundaryPoints.length - 1; i++) { if (Intersector.distanceSegmentPoint(boundaryPoints[i], boundaryPoints[i + 1], source) < MINIMAL_DISPLACEMENT) { return new Vector2[] { boundaryPoints[i], boundaryPoints[i + 1] }; } } throw new IllegalStateException("Expected to find a very close segment"); } // no shortcut possible, and source is not on a segment Vector2 crossOverPoint = new Vector2(); float closest = Float.POSITIVE_INFINITY; Vector2 best = null; int firstSegment = -1; for (int i = 0; i < boundaryPoints.length - 1; i++) { // intersection only makes sense in-to-out; out-to-in would have had // to go out first int relative = Intersector.pointLineSide(justAfterSource, boundaryPoints[i], boundaryPoints[i + 1]); // Gdx.app.log("pf", "Lookup: relative pos is " + relative); if (relative > 0) { if (Intersector.intersectSegments(justAfterSource, target, boundaryPoints[i], boundaryPoints[i + 1], crossOverPoint)) { float dst2 = crossOverPoint.dst2(source); if (dst2 < closest) { closest = dst2; best = crossOverPoint; firstSegment = i; } } } } if (firstSegment == -1) { throw new IllegalStateException("Expected to intersect something, since there was no direct path."); } Vector2[] result; if (!recursive) { // return the closest intersection, as requested result = new Vector2[] { best }; } else { // recursion: endpoints from source to each intersected-segment Vector2[] r1 = lineEndpoints(source, boundaryPoints[firstSegment], false); Vector2[] r2 = lineEndpoints(source, boundaryPoints[firstSegment + 1], false); result = new Vector2[r1.length + r2.length]; System.arraycopy(r1, 0, result, 0, r1.length); System.arraycopy(r2, 0, result, r1.length, r2.length); } return result; }
From source file:headmade.arttag.Guard.java
License:Apache License
public void update(ArtTagScreen artTag, float delta) { if (body == null) { return;//from w ww. j a v a 2 s . c o 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:us.thirdmillenium.strategicassaultsimulator.agents.PuppetAgent.java
License:Apache License
@Override public void updateAgent(float deltaTime) { // Bounds Check - Do nothing if (this.CurrentPath == null) { return;//from ww w .j a va 2s . c o m } else if (this.CurrentPath.getCount() < 1 || this.CurrentPathIndex < 0) { //writeTrainingData(); this.CurrentPath = null; return; } this.agentShoot = 0; // First, calculate inputs double[] timeStepData = calculateTrainingInputs(); // Collect next intermediate node to move to TileNode tempTile = this.CurrentPath.get(this.CurrentPathIndex); // Calculate pixel distance between positions Vector2 currentPosition = this.position.cpy(); Vector2 nextPosition = tempTile.getPixelVector2(); float distance = currentPosition.dst2(nextPosition); // Make sure to move as far as possible if (distance < (Params.AgentMaxMovement * Params.AgentMaxMovement)) { if (this.CurrentPathIndex + 1 < this.CurrentPath.getCount()) { this.CurrentPathIndex++; tempTile = this.CurrentPath.get(this.CurrentPathIndex); nextPosition = tempTile.getPixelVector2(); } else { // We have arrived! this.position.set(nextPosition.x, nextPosition.y); this.Sprite.setCenter(nextPosition.x, nextPosition.y); // Clear Path this.CurrentPath = null; this.CurrentPathIndex = -1; // Write Data //writeTrainingData(); return; } } // Collect angle information from direction Vector2 direction = nextPosition.cpy().sub(currentPosition).nor(); float desiredAngle = direction.angle() - 90; // The angle the sprite should be pointing (90 deg shift) desiredAngle = (desiredAngle < 0) ? 360 + desiredAngle : desiredAngle; // Bring back to 0 - 360 float wantedAngleChange = desiredAngle - this.Angle; // How much angle needs to be added between current angle and desired angle. // Rotate in shortest direction if (wantedAngleChange >= 180) { wantedAngleChange -= 360; } else if (wantedAngleChange <= -180) { wantedAngleChange += 360; } this.deltaAngle = wantedAngleChange; // Check that turn is legal (i.e. within Max Turn Per Frame) if (Math.abs(this.deltaAngle) > Params.AgentMaxTurnAngle) { this.deltaAngle = this.deltaAngle > 0 ? Params.AgentMaxTurnAngle : -Params.AgentMaxTurnAngle; } // Update Position this.position.x += direction.x * Params.AgentMaxMovement; this.position.y += direction.y * Params.AgentMaxMovement; this.Sprite.setCenter(this.position.x, this.position.y); // Update Rotation this.Angle += this.deltaAngle; // Keep between 0 and 360 (sanity purposes) if (this.Angle > 360) { this.Angle -= 360; } else if (this.Angle < 0) { this.Angle += 360; } this.Sprite.setRotation(this.Angle); // Tack on Training Outputs from observed change calculateTrainingOutputs(timeStepData, 52); // Finally, store snapshot of this time step for training this.trainingData.add(timeStepData); }