List of usage examples for com.badlogic.gdx.math Vector2 angle
public float angle(Vector2 reference)
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 av a2 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:headmade.arttag.Player.java
License:Apache License
public void update(ArtTagScreen artTag, float delta) { deltaInLevel += delta;// w w w . j a v a 2s. co m if (body == null) { return; } if (hintText != null) { artTag.setInstruction(hintText); } final float moveSpeed = isRunning ? walkSpeed * runFactor : walkSpeed; final Vector2 oldMoveVec = targetMoveVec.cpy(); targetMoveVec.x = 0f; targetMoveVec.y = 0f; if (isMoveDown) { targetMoveVec.add(0, -moveSpeed); } if (isMoveUp) { targetMoveVec.add(0, moveSpeed); } if (isMoveLeft) { targetMoveVec.add(-moveSpeed, 0); } if (isMoveRight) { targetMoveVec.add(moveSpeed, 0); } 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; // Gdx.app.log(TAG, "oldMoveVec " + oldMoveVec + " targetMoveVec" + targetMoveVec + "sumDeltaSinceMoveChange " // + sumDeltaSinceMoveChange + " - alpha " + alpha); // moveVec.interpolate(targetMoveVec, alpha, Interpolation.linear); body.setLinearVelocity(targetMoveVec); final Vector2 bodyRotVec = new Vector2(1f, 0f); bodyRotVec.setAngleRad(body.getAngle()); final float 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 player moving? if (!MathUtils.isEqual(targetMoveVec.len2(), 0f)) { getStepSound().setVolume(stepSoundId, isRunning ? STEP_VOLUME * 2 : STEP_VOLUME); getStepSound().setPitch(stepSoundId, isRunning ? runFactor : 1f); body.setTransform(body.getPosition(), body.getAngle() + rotByRad); } else { getStepSound().setVolume(stepSoundId, 0f); getStepSound().setPitch(stepSoundId, 1f); } playerLight.setActive(isLightOn); imageAlpha = 0f; if (isLightOn) { for (final Fixture fixture : artInView) { final Vector2 point = fixture.getBody().getWorldCenter(); final boolean isInLight = Player.instance.playerLight.contains(point.x, point.y); if (isInLight || isTouchingArt) { final float distance = point.cpy().dst(body.getWorldCenter()); final float newAlpha = 1 - distance / (playerLightLength * PLAYERLIGHT_CONE_LENGTH_FACTOR); if (newAlpha > imageAlpha) { // Gdx.app.log(TAG, "distance " + distance + " alpha " + newAlpha); imageAlpha = newAlpha; if (!((Art) fixture.getBody().getUserData()).equals(artTag.getCurrentArt())) { artTag.setCurrentArt((Art) fixture.getBody().getUserData()); } if (artTag.getCurrentArt().isScanned()) { artTag.setInstruction(MSG_SCAN_3); } else { artTag.setInstruction(MSG_SCAN); } } } } } if (inventory.size >= carryCacity) { artTag.setInstruction(MSG_INVENTORY_FULL); } if (isTouchingExit) { artTag.setInstruction(MSG_DOOR); } if (isScanning) { artTag.setInstruction(MSG_SCAN_2); if (!isTouchingArt || !isLightOn) { // abort scan isScanning = false; sumDeltaScan = 0f; // TODO cancel scan sound } else { scanProgress = Math.round(sumDeltaScan / scanTime * new Float(SCANNING_PROGRESS.length - 1));// (scanProgress + 1) % // SCANNING_PROGRESS.length; artTag.setResult(" Scanning " + SCANNING_PROGRESS[scanProgress]); sumDeltaScan += delta; if (sumDeltaScan > scanTime) { artTag.getCurrentArt().onScanFinished(artTag); artTag.setResult(artTag.getCurrentArt().resultText()); isScanning = false; sumDeltaScan = 0f; // TODO cancel scan sound artTag.getCurrentArt().setScanned(true); artTag.setInstruction(MSG_SCAN_3); TagService.instance.tag(artTag.getCurrentArt(), artTag.jobDescription); } } } isAbleToScan = !isScanning && isTouchingArt && artTag.getCurrentArt() != null && !artTag.getCurrentArt().isScanned(); isAbleToSteal = isTouchingArt && artTag.getCurrentArt() != null && artTag.getCurrentArt().isScanned() && inventory.size < carryCacity; }
From source file:us.thirdmillenium.strategicassaultsimulator.agents.PuppetAgent.java
License:Apache License
private double[] calculateTrainingInputs() { double[] timeStepData = new double[74]; //timeStepData[0] =(double)( Math.abs(this.Angle) > 360 ? (this.Angle / 360) : (this.Angle / 360) ); if (this.Angle > 360) { timeStepData[0] = (double) ((this.Angle - 360) / 360); } else if (this.Angle < -360) { timeStepData[0] = (double) ((this.Angle + 720) / 360); } else if (this.Angle < 0) { timeStepData[0] = (double) ((this.Angle + 360) / 360); } else {/*from ww w . ja v a2s. c o m*/ timeStepData[0] = (double) (this.Angle / 360); } // Angle to Bullets within 3 tiles (Max of 2) int count = 1; Iterator<GreenBullet> bulletITR = this.bullets.iterator(); while (bulletITR.hasNext() && count < 3) { GreenBullet currBullet = bulletITR.next(); if (position.dst(currBullet.getBulletVector()) < (Params.MapTileSize * 3)) { Vector2 direction = currBullet.getBulletVector().cpy().sub(position).nor(); Vector2 unitVec = new Vector2(0, 1); timeStepData[count++] = (double) (unitVec.angle(direction) / 360); } } // When no bullets, its just 0. timeStepData[1] = (count > 1) ? timeStepData[1] : 1; timeStepData[2] = (count > 2) ? timeStepData[2] : 1; // Feed in the 7x7 array of values int cellX = (int) (this.position.x / Params.MapTileSize); int cellY = (int) (this.position.y / Params.MapTileSize); int currentCellIndex = (cellX * Params.NumCellsY) + cellY; int gridYCount = 0; int gridXCount = 0; // Compute from Bottom Left to Top Right - note that it is (Col,Row) for (int gridY = cellY - 3; gridY <= cellY + 3; gridY++) { if (gridY >= 0 && gridY < Params.NumCellsY) { gridXCount = 0; for (int gridX = cellX - 3; gridX <= cellX + 3; gridX++) { if (gridX >= 0 && gridX < Params.NumCellsX) { // Compute indexes int tileIndex = (gridX * Params.NumCellsY) + gridY; int inputIndex = ((6 - gridYCount) * 7) + gridXCount + 3; //((6-colCount)*7)+rowCount+1; // Check if cell is traversable if (this.MapNodes.containsKey(tileIndex)) { //TileNode tester = this.traverseNodes.get(tileIndex); // Its traversable, so at least a 1 timeStepData[inputIndex] = (1 / (double) 5); // Check if player is currently located there if (tileIndex == currentCellIndex) { timeStepData[inputIndex] = (2 / (double) 5); } // Check if contains a preferred path node if (this.currPathNodeTracker.contains(this.MapNodes.get(tileIndex))) { timeStepData[inputIndex] = (3 / (double) 5); } // Check if contains a friendly /*Iterator<TrainingAgent> friendlyITR = this.trainees.iterator(); while(friendlyITR.hasNext()) { TrainingAgent tempFriendly = friendlyITR.next(); if( tempFriendly != this && tileIndex == tempFriendly.getTraverseNodeIndex() ) { timeStepData[inputIndex] = (4 / (double)5); } }*/ // Check if contains an enemy Iterator<AgentModel> shooterITR = this.shooters.iterator(); while (shooterITR.hasNext()) { AgentModel tempShooter = shooterITR.next(); if (tileIndex == tempShooter.getTraverseNodeIndex()) { timeStepData[inputIndex] = (5 / (double) 5); this.agentShoot = 1; } } } } gridXCount++; } } gridYCount++; } return timeStepData; }
From source file:us.thirdmillenium.strategicassaultsimulator.agents.TrainingAgent.java
License:Apache License
@Override public void updateAgent(float deltaTime) { // Vars/*from w w w . ja v a 2 s .c o m*/ double[] inputs = new double[this.brain.getNumInputs()]; double gridNorm = 5; double angleNorm = 360; /* * Collect information into double[] array for brain crunching */ // Current Rotation inputs[0] = this.rotation / angleNorm; // Angle to Bullets within 3 tiles (Max of 2) int count = 1; Iterator<GreenBullet> bulletITR = this.bullets.iterator(); while (bulletITR.hasNext() && count < 3) { GreenBullet currBullet = bulletITR.next(); if (this.position.dst(currBullet.getBulletVector()) < (Params.MapTileSize * 3)) { Vector2 direction = currBullet.getBulletVector().cpy().sub(this.position).nor(); Vector2 unitVec = new Vector2(0, 1); inputs[count++] = unitVec.angle(direction) / angleNorm; } } // When no bullets, its just 0. inputs[1] = (count > 1) ? inputs[1] : 1; inputs[2] = (count > 2) ? inputs[2] : 1; // Feed in the 7x7 array of values int cellX = (int) (this.position.x / Params.MapTileSize); int cellY = (int) (this.position.y / Params.MapTileSize); int currentCellIndex = (cellX * Params.NumCellsY) + cellY; int gridYCount = 0; int gridXCount = 0; // Compute from Bottom Left to Top Right - note that it is (Col,Row) for (int gridY = cellY - 3; gridY <= cellY + 3; gridY++) { if (gridY >= 0 && gridY < Params.NumCellsY) { gridXCount = 0; for (int gridX = cellX - 3; gridX <= cellX + 3; gridX++) { if (gridX >= 0 && gridX < Params.NumCellsX) { // Compute indexes int tileIndex = (gridX * Params.NumCellsY) + gridY; int inputIndex = ((6 - gridYCount) * 7) + gridXCount + 3; //((6-colCount)*7)+rowCount+1; // Check if cell is traversable if (this.traverseNodes.containsKey(tileIndex)) { //TileNode tester = this.traverseNodes.get(tileIndex); // Its traversable, so at least a 1 inputs[inputIndex] = 1 / gridNorm; // Check if player is currently located there if (tileIndex == currentCellIndex) { inputs[inputIndex] = 2 / gridNorm; } // Check if contains a preferred path node if (this.prefPathNodeTracker.contains(this.traverseNodes.get(tileIndex))) { inputs[inputIndex] = 3 / gridNorm; } // Check if contains a friendly Iterator<AgentModel> friendlyITR = this.trainees.iterator(); while (friendlyITR.hasNext()) { AgentModel tempFriendly = friendlyITR.next(); if (tempFriendly != this && tileIndex == tempFriendly.getTraverseNodeIndex()) { inputs[inputIndex] = 4 / gridNorm; } } // Check if contains an enemy Iterator<AgentModel> shooterITR = this.shooters.iterator(); while (shooterITR.hasNext()) { AgentModel tempShooter = shooterITR.next(); if (tileIndex == tempShooter.getTraverseNodeIndex()) { inputs[inputIndex] = 5 / gridNorm; } } } } gridXCount++; } } gridYCount++; } /* * Get Brain Response */ double[] outputs = this.brain.brainCrunch(inputs); /* * Update Agent based on Response */ // Collect output groupings double[] rotationOutput = new double[7]; double[] gunRotationOutput = new double[7]; double[] velocityOutput = new double[7]; double shoot = outputs[outputs.length - 1]; for (int i = 0; i < 7; i++) { rotationOutput[i] = outputs[i]; gunRotationOutput[i] = outputs[i + 7]; velocityOutput[i] = outputs[i + 14]; } // Update updatePosition(rotationOutput, velocityOutput, deltaTime); updateShooting(gunRotationOutput, shoot); // Debug //if( ++this.counter % 1000 == 0 ) { System.out.println("Counter = " + this.counter + " Score: " + this.score); } }
From source file:us.thirdmillenium.strategicassaultsimulator.agents.TrainingShooter.java
License:Apache License
/** * If Agent is alive, will scan surrounding for Trainee, and fire at it if not in cooldown. */// w w w . jav a 2s. c om public void updateAgent(float timeDiff) { // Check if Agent can shoot now if (!this.canShoot) { this.timeSinceLastShot += timeDiff; if (this.timeSinceLastShot > Params.AgentFireRate) { this.timeSinceLastShot = 0; this.canShoot = true; } else { return; } } // If Agent is alive and can shoot, scan for target in range. if (this.alive && this.canShoot) { // If a Trainee has wondered within firing range, fire at it. Iterator<AgentModel> itr = this.trainees.iterator(); while (itr.hasNext()) { AgentModel trainee = itr.next(); Vector2 traineePosition = trainee.getPosition(); // Trainee in Range, Shoot it! if (this.position.dst(traineePosition) < (Params.MapTileSize * 3)) { Vector2 direction = traineePosition.cpy().sub(this.position).nor(); Vector2 unitVec = new Vector2(0, 1); float angle = unitVec.angle(direction); this.sprite.setRotation(angle); this.bulletTracker.add(new GreenBullet(new Vector2(this.position.x, this.position.y), calcFireAngle(angle), this)); this.canShoot = false; this.timeSinceLastShot = 0; return; } } } }
From source file:vault.clockwork.actors.HandActor.java
License:Open Source License
/** * Calculate angle difference of hand by a given vector. * @param by/*from w w w. j a v a 2 s . co m*/ * @return */ private float angleDifference(Vector2 by) { return by.angle(Vector2.X.cpy().setAngle(sprHand.getRotation())); }