List of usage examples for com.badlogic.gdx.math Vector2 angle
public float angle()
From source file:com.uwsoft.editor.view.stage.tools.TransformTool.java
License:Apache License
@Override public void anchorDragged(NormalSelectionFollower follower, int anchor, float x, float y) { Sandbox sandbox = Sandbox.getInstance(); Vector2 mousePointStage = sandbox.screenToWorld(x, y); x = mousePointStage.x;//from w w w . j a v a 2s . c o m y = mousePointStage.y; TransformComponent transformComponent = ComponentRetriever.get(follower.getEntity(), TransformComponent.class); DimensionsComponent dimensionsComponent = ComponentRetriever.get(follower.getEntity(), DimensionsComponent.class); float newX = transformComponent.x; float newY = transformComponent.y; float newWidth = dimensionsComponent.width * transformComponent.scaleX; float newHeight = dimensionsComponent.height * transformComponent.scaleY; float newOriginX = transformComponent.originX; float newOriginY = transformComponent.originY; float tmpAdjustmenX = transformComponent.originX * (transformComponent.scaleX - 1); float tmpAdjustmenY = transformComponent.originY * (transformComponent.scaleY - 1); final float cos = MathUtils.cosDeg(transformComponent.rotation); final float sin = MathUtils.sinDeg(transformComponent.rotation); float difX = (transformComponent.x - x); float difY = (transformComponent.y - y); difX = (difX * cos + difY * sin); difY = (difX * -sin + difY * cos); switch (anchor) { case NormalSelectionFollower.ORIGIN: //TODO this shit is to complicated will leave it for now // newOriginX = x - transformComponent.x; // newOriginY = y - transformComponent.y; // TODO: adjust coordinates //final float cos = (float)Math.cos(transformComponent.rotation * MathUtils.degreesToRadians); //final float sin = (float)Math.sin(transformComponent.rotation * MathUtils.degreesToRadians); //final float tox = (localCoords.x - originX) * scaleX; //final float toy = (localCoords.y - originY) * scaleY; //newX = (newX * cos + newY * sin)+newX; //newY = (newX * -sin + newY * cos)+newY; break; case NormalSelectionFollower.L: newWidth = dimensionsComponent.width + difX * 2; break; case NormalSelectionFollower.R: newWidth = tmpAdjustmenX - difX; break; case NormalSelectionFollower.B: newHeight = dimensionsComponent.height + difY * 2; break; case NormalSelectionFollower.T: newHeight = tmpAdjustmenY - difY; break; case NormalSelectionFollower.LT: newWidth = dimensionsComponent.width + difX * 2; newHeight = tmpAdjustmenY - difY; break; case NormalSelectionFollower.RT: newWidth = tmpAdjustmenX - difX; newHeight = tmpAdjustmenY - difY; break; case NormalSelectionFollower.RB: newWidth = tmpAdjustmenX - difX; newHeight = dimensionsComponent.height + difY * 2; break; case NormalSelectionFollower.LB: newWidth = dimensionsComponent.width + difX * 2; newHeight = dimensionsComponent.height + difY * 2; break; } if (Gdx.input.isKeyPressed(Input.Keys.SHIFT_LEFT)) { float enclosingRectSize = Math.max(newWidth, newHeight); if (dimensionsComponent.width >= dimensionsComponent.height) { newWidth = enclosingRectSize; newHeight = (newWidth / dimensionsComponent.width) * dimensionsComponent.height; } if (dimensionsComponent.height > dimensionsComponent.width) { newHeight = enclosingRectSize; newWidth = (newHeight / dimensionsComponent.height) * dimensionsComponent.width; } } if (anchor != NormalSelectionFollower.ORIGIN) { newOriginX = (newWidth / (dimensionsComponent.width * transformComponent.scaleX)) * newOriginX; newOriginY = (newHeight / (dimensionsComponent.height * transformComponent.scaleY)) * newOriginY; } if (anchor >= NormalSelectionFollower.ROTATION_LT && anchor <= NormalSelectionFollower.ROTATION_LB) { Vector2 originPoint = new Vector2(transformComponent.x + transformComponent.originX, transformComponent.y + transformComponent.originY); mousePointStage.sub(originPoint); float currentAngle = mousePointStage.angle(); float angleDiff = currentAngle - lastTransformAngle; transformComponent.rotation = lastEntityAngle + angleDiff; } //transformComponent.y = newY; if (EntityUtils.getType(follower.getEntity()) == EntityFactory.NINE_PATCH) { NinePatchComponent ninePatchComponent = ComponentRetriever.get(follower.getEntity(), NinePatchComponent.class); if (newWidth < ninePatchComponent.ninePatch.getTotalWidth()) newWidth = ninePatchComponent.ninePatch.getTotalWidth(); if (newHeight < ninePatchComponent.ninePatch.getTotalHeight()) newHeight = ninePatchComponent.ninePatch.getTotalHeight(); dimensionsComponent.width = newWidth; dimensionsComponent.height = newHeight; } else { transformComponent.scaleX = newWidth / dimensionsComponent.width; transformComponent.scaleY = newHeight / dimensionsComponent.height; } transformComponent.x = newX; transformComponent.y = newY; //transformComponent.originX = newOriginX; //transformComponent.originY = newOriginY; Overlap2DFacade.getInstance().sendNotification(Overlap2D.ITEM_DATA_UPDATED); }
From source file:com.vlaaad.dice.game.world.view.visualizers.actions.PoisonDartVisualizer.java
License:Open Source License
@Override public IFuture<Void> visualize(PoisonShotResult result) { final Future<Void> future = new Future<Void>(); final WorldObjectView actorView = visualizer.viewController.getView(result.creature); WorldObjectView targetView = visualizer.viewController.getView(result.target); Vector2 direction = tmp.set(result.target.getX(), result.target.getY()).sub(result.creature.getX(), result.creature.getY());/*from w w w . j av a2 s . c o m*/ visualizer.viewController.scroller.centerOn(result.target); float dx = targetView.getX() - actorView.getX(); float dy = targetView.getY() - actorView.getY(); final ImageSubView arrow = new ImageSubView("animation/poison-dart"); arrow.getActor().setOrigin(13, 14); arrow.getActor().setRotation(direction.angle()); arrow.getActor().addAction(Actions.sequence(Actions.moveBy(dx, dy, tmp.set(dx, dy).len() * 0.003f), Actions.run(new Runnable() { @Override public void run() { SoundManager.instance.playSound("arrow-shot"); actorView.removeSubView(arrow); future.happen(); } }))); actorView.addSubView(arrow); return future; }
From source file:com.vlaaad.dice.game.world.view.visualizers.CommonShotVisualizer.java
License:Open Source License
@Override public IFuture<Void> visualize(final T result) { final Future<Void> future = Future.make(); final WorldObjectView actorView = visualizer.viewController.getView(result.getActor()); WorldObjectView targetView = visualizer.viewController.getView(result.getTarget()); visualizer.viewController.world.dispatcher.dispatch(ResultVisualizer.VISUALIZE_ATTACK, result.getActor()); Vector2 direction = tmp.set(result.getTarget().getX(), result.getTarget().getY()) .sub(result.getActor().getX(), result.getActor().getY()); float dx = targetView.getX() - actorView.getX(); float dy = targetView.getY() - actorView.getY(); visualizer.viewController.scroller.centerOn(result.getTarget()); final Image arrow = new Image(Config.skin, "animation/" + result.getAbility().name + "-shot"); arrow.setPosition(actorView.getX(), actorView.getY()); visualizer.viewController.effectLayer.addActor(arrow); arrow.setOrigin(13, 14);//w w w . j a v a 2 s . c o m arrow.setRotation(direction.angle() - 45); arrow.addAction(Actions.sequence(Actions.moveBy(dx, dy, tmp.set(dx, dy).len() * 0.002f), Actions.run(new Runnable() { @Override public void run() { SoundManager.instance.playSoundIfExists(result.getAbility().soundName); arrow.remove(); future.happen(); } }))); return future; }
From source file:com.vlaaad.dice.game.world.view.visualizers.ShotVisualizer.java
License:Open Source License
@Override public IFuture<Void> visualize(final ShotResult result) { final Future<Void> future = new Future<Void>(); final WorldObjectView actorView = visualizer.viewController.getView(result.creature); WorldObjectView targetView = visualizer.viewController.getView(result.target); visualizer.viewController.world.dispatcher.dispatch(ResultVisualizer.VISUALIZE_ATTACK, result.creature); Vector2 direction = tmp.set(result.target.getX(), result.target.getY()).sub(result.creature.getX(), result.creature.getY());//from w w w. j av a 2 s .c om float dx = targetView.getX() - actorView.getX(); float dy = targetView.getY() - actorView.getY(); visualizer.viewController.scroller.centerOn(result.target); final ImageSubView arrow = new ImageSubView("animation/arrow-" + result.attackLevel); arrow.getActor().setOrigin(13, 14); arrow.getActor().setRotation(direction.angle() - 45); visualizer.viewController.visualize(new Defence(result.target, result.type)); arrow.getActor().addAction(Actions.sequence(Actions.moveBy(dx, dy, tmp.set(dx, dy).len() * 0.002f), Actions.run(new Runnable() { @Override public void run() { SoundManager.instance.playSound("arrow-shot"); actorView.removeSubView(arrow); if (result.success) { visualizer.viewController.visualize(new Death(result.creature, result.target)) .addListener(future); } else { future.happen(); } } }))); actorView.addSubView(arrow); return future; }
From source file:es.eucm.ead.editor.view.widgets.groupeditor.Modifier.java
License:Open Source License
/** * Applies the current transformation represented by the handles to given * actor/*from w ww . j a v a 2s . c o m*/ */ public void applyTransformation(Actor influencedActor, Vector2 origin, Vector2 tangent, Vector2 normal) { /* * We are going to calculate the affine transformation for the actor to * fit the bounds represented by the handles. The affine transformation * is defined as follows: */ // |a b tx| // |c d ty|=|Translation Matrix| x |Scale Matrix| x |Rotation // Matrix| // |0 0 1 | /* * More info about affine transformations: * https://people.gnome.org/~mathieu * /libart/libart-affine-transformation-matrices.html, To obtain the * matrix, we want to resolve the following equation system: */ // | a b tx| |0| |o.x| // | c d ty|*|0|=|o.y| // | 0 0 1 | |1| | 1 | // // | a b tx| |w| |t.x| // | c d ty|*|0|=|t.y| // | 0 0 1 | |1| | 1 | // // | a b tx| |0| |n.x| // | c d ty|*|h|=|n.y| // | 0 0 1 | |1| | 1 | /* * where o is handles[0] (origin), t is handles[2] (tangent) and n is * handles[6] (normal), w is actor.getWidth() and h is * actor.getHeight(). * * This matrix defines that the 3 points defining actor bounds are * transformed to the 3 points defining modifier bounds. E.g., we want * that actor origin (0,0) is transformed to (handles[0].x, * handles[0].y), and that is expressed in the first equation. * * Resolving these equations is obtained: */ // a = (t.x - o.y) / w // b = (t.y - o.y) / w // c = (n.x - o.x) / h // d = (n.y - o.y) / h /* * Values for translation, scale and rotation contained by the matrix * can be obtained directly making operations over a, b, c and d: */ // tx = o.x // ty = o.y // sx = sqrt(a^2+b^2) // sy = sqrt(c^2+d^2) // rotation = atan(c/d) // or // rotation = atan(-b/a) /* * Rotation can give two different values (this happens when there is * more than one way of obtaining the same transformation). To avoid * that, we ignore the rotation to obtain the final values. */ Vector2 o = tmp1.set(origin.x, origin.y); Vector2 t = tmp2.set(tangent.x, tangent.y); Vector2 n = tmp3.set(normal.x, normal.y); Vector2 vt = tmp4.set(t).sub(o); Vector2 vn = tmp5.set(n).sub(o); // Ignore rotation float rotation = influencedActor.getRotation(); vt.rotate(-rotation); vn.rotate(-rotation); t.set(vt).add(o); n.set(vn).add(o); float a = (t.x - o.x) / influencedActor.getWidth(); float c = (t.y - o.y) / influencedActor.getWidth(); float b = (n.x - o.x) / influencedActor.getHeight(); float d = (n.y - o.y) / influencedActor.getHeight(); // Math.sqrt gives a positive value, but it also have a negatives. // The // signum is calculated computing the current rotation float signumX = vt.angle() > 90.0f && vt.angle() < 270.0f ? -1.0f : 1.0f; float signumY = vn.angle() > 180.0f ? -1.0f : 1.0f; float scaleX = (float) Math.sqrt(a * a + b * b) * signumX; float scaleY = (float) Math.sqrt(c * c + d * d) * signumY; influencedActor.setScale(scaleX, scaleY); /* * To obtain the correct translation value we need to subtract the * amount of translation due to the origin. */ tmpMatrix.setToTranslation(influencedActor.getOriginX(), influencedActor.getOriginY()); tmpMatrix.rotate(influencedActor.getRotation()); tmpMatrix.scale(influencedActor.getScaleX(), influencedActor.getScaleY()); tmpMatrix.translate(-influencedActor.getOriginX(), -influencedActor.getOriginY()); /* * Now, the matrix has how much translation is due to the origin * involved in the rotation and scaling operations */ float x = o.x - tmpMatrix.getValues()[Matrix3.M02]; float y = o.y - tmpMatrix.getValues()[Matrix3.M12]; influencedActor.setPosition(x, y); }
From source file:es.eucm.ead.engine.utils.EngineUtils.java
License:Open Source License
/** * Sets position, rotation, scale and origin in actor to meet the 3 given * points/*www. j a v a2 s .co m*/ */ public static void applyTransformation(Actor actor, Vector2 origin, Vector2 tangent, Vector2 normal) { /* * We are going to calculate the affine transformation for the actor to * fit the bounds represented by the handles. The affine transformation * is defined as follows: */ // |a b tx| // |c d ty|=|Translation Matrix| x |Scale Matrix| x |Rotation // Matrix| // |0 0 1 | /* * More info about affine transformations: * https://people.gnome.org/~mathieu * /libart/libart-affine-transformation-matrices.html, To obtain the * matrix, we want to resolve the following equation system: */ // | a b tx| |0| |o.x| // | c d ty|*|0|=|o.y| // | 0 0 1 | |1| | 1 | // // | a b tx| |w| |t.x| // | c d ty|*|0|=|t.y| // | 0 0 1 | |1| | 1 | // // | a b tx| |0| |n.x| // | c d ty|*|h|=|n.y| // | 0 0 1 | |1| | 1 | /* * where o is handles[0] (origin), t is handles[2] (tangent) and n is * handles[6] (normal), w is actor.getWidth() and h is * actor.getHeight(). * * This matrix defines that the 3 points defining actor bounds are * transformed to the 3 points defining modifier bounds. E.g., we want * that actor origin (0,0) is transformed to (handles[0].x, * handles[0].y), and that is expressed in the first equation. * * Resolving these equations is obtained: */ // a = (t.x - o.y) / w // b = (t.y - o.y) / w // c = (n.x - o.x) / h // d = (n.y - o.y) / h /* * Values for translation, scale and rotation contained by the matrix * can be obtained directly making operations over a, b, c and d: */ // tx = o.x // ty = o.y // sx = sqrt(a^2+b^2) // sy = sqrt(c^2+d^2) // rotation = atan(c/d) // or // rotation = atan(-b/a) /* * Rotation can give two different values (this happens when there is * more than one way of obtaining the same transformation). To avoid * that, we ignore the rotation to obtain the final values. */ Vector2 tmp1 = Pools.obtain(Vector2.class); Vector2 tmp2 = Pools.obtain(Vector2.class); Vector2 tmp3 = Pools.obtain(Vector2.class); Vector2 tmp4 = Pools.obtain(Vector2.class); Vector2 tmp5 = Pools.obtain(Vector2.class); Vector2 o = tmp1.set(origin.x, origin.y); Vector2 t = tmp2.set(tangent.x, tangent.y); Vector2 n = tmp3.set(normal.x, normal.y); Vector2 vt = tmp4.set(t).sub(o); Vector2 vn = tmp5.set(n).sub(o); // Ignore rotation float rotation = actor.getRotation(); vt.rotate(-rotation); vn.rotate(-rotation); t.set(vt).add(o); n.set(vn).add(o); Vector2 bottomLeft = Pools.obtain(Vector2.class); Vector2 size = Pools.obtain(Vector2.class); calculateBounds(actor, bottomLeft, size); float a = (t.x - o.x) / size.x; float c = (t.y - o.y) / size.x; float b = (n.x - o.x) / size.y; float d = (n.y - o.y) / size.y; Pools.free(tmp1); Pools.free(tmp2); Pools.free(tmp3); Pools.free(tmp4); Pools.free(tmp5); Pools.free(bottomLeft); Pools.free(size); // Math.sqrt gives a positive value, but it also have a negatives. // The // signum is calculated computing the current rotation float signumX = vt.angle() > 90.0f && vt.angle() < 270.0f ? -1.0f : 1.0f; float signumY = vn.angle() > 180.0f ? -1.0f : 1.0f; float scaleX = (float) Math.sqrt(a * a + b * b) * signumX; float scaleY = (float) Math.sqrt(c * c + d * d) * signumY; actor.setScale(scaleX, scaleY); /* * To obtain the correct translation value we need to subtract the * amount of translation due to the origin. */ tmpMatrix.setToTranslation(actor.getOriginX(), actor.getOriginY()); tmpMatrix.rotate(actor.getRotation()); tmpMatrix.scale(actor.getScaleX(), actor.getScaleY()); tmpMatrix.translate(-actor.getOriginX(), -actor.getOriginY()); /* * Now, the matrix has how much translation is due to the origin * involved in the rotation and scaling operations */ float x = o.x - tmpMatrix.getValues()[Matrix3.M02]; float y = o.y - tmpMatrix.getValues()[Matrix3.M12]; actor.setPosition(x, y); }
From source file:jordanlw.gdxGame.Game.java
License:Open Source License
public void render() { Vector2 bulletVector = new Vector2(); Vector2 relativeMousePosition = new Vector2(); Vector2 distanceToMouse = new Vector2(); Boolean gunFiredThisFrame = false; float delta = Gdx.graphics.getDeltaTime(); movementThisFrame = false;/*from w w w . jav a 2 s .c o m*/ Gdx.gl.glClearColor(0, 0, 0, 0); Gdx.gl.glClear(0); handleEnemyWaves(); //Handle player wanting to pause if (Gdx.input.isKeyJustPressed(Input.Keys.P)) { if (gamePaused) { if (!isGameCreated) { setupGame(); } gamePaused = false; aMusicLibrary.backgroundMusic.play(); } else { gamePaused = true; aMusicLibrary.backgroundMusic.pause(); } } //Does the user want multiplayer? if (Gdx.input.isKeyJustPressed(Input.Keys.M)) { NetworkSetup.getTextInput("Multiplayer Network Address"); } if (Gdx.input.isKeyJustPressed(Input.Keys.H)) { NetworkSetup.getAnswer("Host Multiplayer?"); } if (!gamePaused) { totalTime += delta; for (Player player : players) { player.secondsDamaged -= delta; } //Update player rotation wrt mouse position getLocalPlayer().rotation = (float) Mouse .angleBetween(getLocalPlayer().position.getPosition(new Vector2())); Zombie.zombeGroanSoundTimer += delta; if (Zombie.zombeGroanSoundTimer > 6f) { int index = (int) (Math.random() * (aMusicLibrary.zombieSounds.length - 1)); aMusicLibrary.zombieSounds[index].setVolume(aMusicLibrary.zombieSounds[index].play(), 0.5f * volume); Zombie.zombeGroanSoundTimer = 0; } handleInput(relativeMousePosition, mousePressedPosition, distanceToMouse, bulletVector); //Anything serverside eg. enemy movement, medkit respawning. if (isServer) { if (!aMusicLibrary.backgroundMusic.isPlaying()) { for (Player player : players) { player.health = 0; } } for (Player player : players) { medkit.time += delta; if (medkit.time > Medkit.SECS_TILL_DISAPPEAR && medkit.health <= 0) { medkit.health = Medkit.healthGiven; medkit.position.setPosition((float) (camera.viewportWidth * Math.random()), (float) (camera.viewportHeight * Math.random())); } else if (medkit.time >= Medkit.SECS_TILL_DISAPPEAR && player.position.overlaps(medkit.position)) { player.health += medkit.health; medkit.health = 0; medkit.time = 0; aMusicLibrary.medkitSound.play(0.3f * volume); if (player.health > 100) { player.health = 100; } } for (Zombie enemy : enemies) { if (enemy.health <= 0) { continue; } enemy.secondsDamaged -= delta; Vector2 vecPlayer = new Vector2(); Vector2 vecEnemy = new Vector2(); enemy.position.getPosition(vecEnemy); player.position.getPosition(vecPlayer); Vector2 tmpEnemy = new Vector2( vecPlayer.sub(vecEnemy).nor().scl(delta * enemy.walkingSpeed)); if (player.position.getPosition(new Vector2()) .dst(enemy.position.getPosition(new Vector2())) < 300) { tmpEnemy.rotate(enemy.swarmAngle); } enemy.rotation = tmpEnemy.angle(); tmpEnemy.add(enemy.position.x, enemy.position.y); enemy.position.setPosition(tmpEnemy); } } } //Respond to player pressing mouse button if (mousePressedPosition.x != -1 && mousePressedPosition.y != -1 && getLocalPlayer().health > 0) { //Gun sound for player if (totalTime > timeGunSound) { timeGunSound = totalTime + 0.5f; aMusicLibrary.gunSound.play(0.25f * volume); //aMusicLibrary.gunSound.setPitch(soundId, 1 + (long) (0.3f * Math.random())); gunFiredThisFrame = true; shootingTime = torsoAnimLength; Collections.sort(enemies, new ZombieDistance()); for (Zombie enemy : enemies) { if (enemy.health <= 0) { continue; } Vector2 vecPlayer = new Vector2(); getLocalPlayer().position.getCenter(vecPlayer); float angle = (float) Mouse.angleBetween(vecPlayer); Vector2 vecAngle = new Vector2(vecPlayer); Vector2 tmp = new Vector2(1, 1); tmp.setAngle(angle).nor().scl(98765); vecAngle.add(tmp); if (Intersector.intersectSegmentCircle(vecPlayer, vecAngle, enemy.position.getCenter(new Vector2()), (enemy.position.width / 2) * (enemy.position.width / 2))) { enemy.secondsDamaged = 0.5f; enemy.health -= 35; if (enemy.health <= 0) { gold.saveEnemy(currentWave, enemies.indexOf(enemy)); } break; } } } } } camera.update(); batch.setProjectionMatrix(camera.combined); batch.begin(); batch.setColor(Color.WHITE); for (int width = 0; width < windowSize.x; width += backgroundTexture.getWidth()) { for (int height = 0; height < windowSize.y; height += backgroundTexture.getHeight()) { batch.draw(backgroundTexture, width, height); } } medkit.draw(batch); gold.draw(batch); //Draw enemies for (Zombie enemy : enemies) { enemy.draw(batch, totalTime); } batch.setColor(Color.WHITE); for (Player player : players) { player.draw(batch, totalTime, delta); } if (getLocalPlayer().health <= 0) { batch.draw(gameOverTexture, camera.viewportWidth / 2 - gameOverTexture.getWidth() / 2, camera.viewportHeight / 2 - gameOverTexture.getHeight() / 2); } else if (gamePaused) { batch.draw(gameStartTexture, camera.viewportWidth / 2 - gameStartTexture.getWidth() / 2, camera.viewportHeight / 2 - gameStartTexture.getHeight() / 2); } batch.setColor(Color.YELLOW); if (gunFiredThisFrame) { //noinspection SuspiciousNameCombination batch.draw(singlePixel, getLocalPlayer().position.x, getLocalPlayer().position.y, 0, 0, 1, 1, 1, distanceToMouse.x, 180 + (float) Math.toDegrees( Math.atan2((double) relativeMousePosition.x, (double) relativeMousePosition.y))); } batch.end(); isLeftMousePressedThisFrame = false; mousePressedPosition.set(-1, -1); }
From source file:org.destinationsol.common.SolMath.java
License:Apache License
/** * @return angle of a vector. if not precise, approximation is returned. * (1, 0) is right and 0 degrees/*from www . j a v a 2 s.c om*/ * (0, 1) is down and 90 degrees * (-1, 0) is left and 180 degrees * (0, -1) is up and -90 degrees */ public static float angle(Vector2 v, boolean precise) { if (precise) return v.angle(); else return MathUtils.atan2(v.y, v.x) * radDeg; }
From source file:us.notsoserio.ninja.weapons.projectiles.ProjectileFactory.java
License:Apache License
public static Projectile CreateProjectile(byte projectileType, Vector2 trajectory, Entity owner, World levelWorld) {//from w w w . j a va 2 s. c o m Projectile projectile; switch (projectileType) { case Projectiles.Kunai: projectile = new Kunai(owner, trajectory.angle(), true); break; default: return null; } projectile.VelocityX = trajectory.x; projectile.VelocityY = trajectory.y; projectile.X = owner.X + owner.Width / 2; projectile.Y = owner.Y + 2 * owner.Height / 3; BodyDef bodyDef = new BodyDef(); bodyDef.type = BodyDef.BodyType.DynamicBody; bodyDef.position.set(new Vector2(projectile.X, projectile.Y)); Body body = levelWorld.createBody(bodyDef); projectile.ApplyBody(body); body.setUserData(projectile); body.setBullet(true); body.setTransform(projectile.X, projectile.Y, projectile.rotation * (float) (Math.PI / 180)); body.applyLinearImpulse(projectile.VelocityX, projectile.VelocityY, projectile.X, projectile.Y, true); if (Gdx.app.getType() != Application.ApplicationType.HeadlessDesktop) projectile.CreateDrawable(); return projectile; }
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;// ww w. j a v a 2s . co 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); }