List of usage examples for com.badlogic.gdx.math Vector2 rotate
public Vector2 rotate(float degrees)
From source file:es.eucm.ead.engine.utils.ShapeToCollider.java
License:Open Source License
/** * Builds a circumscribed polygon for a {@code circle} that can be used as a * collider./*from www.j a v a 2s .com*/ * * The number of sides of the polygon is specified through param * {@code nSides}. * * The algorithm to calculate the minimum nSides polygon that covers a * circle (circumscribed) is as follows: * * (To see what a circumscribed polygon is, visit: <a href= * "http://www.vitutor.com/geometry/plane/circumscribed_polygons.html" * >http://www.vitutor.com/geometry/plane/circumscribed_polygons.html</a>) * * 1) Distance from circle's center to each vertex (equidistant) is * calculated (d). * * 2) A vector with length d is calculated. * * 3) Vector is added to the circle's center to get one vertex. * * 4) The vector is rotated "a" degrees. "a" is calculated by dividing 360 * by the number of sides of the polygon. * * (3) and (4) are repeated until all the vertices are calculated. * * Note: d=r/cos(a/2), where: r: circle's radius a: angle * * See <a href="https://github.com/e-ucm/ead/wiki/Shape-renderer">This wiki * page</a> for more details */ public static Polygon buildCircleCollider(Circle circle, int nSides) { Polygon polygon = new Polygon(); float vertices[] = new float[nSides * 2]; // The radius float r = circle.getRadius(); // The center of the circle. Since we work on a coordinate system where // the origin is in the bottom-left corner of the element, the center is // located in (radius, radius). float cx = r, cy = r; // How much we must rotate the radius vector (normal to the circle) float angleInc = 360.0F / nSides; double halfAngleIncRad = Math.PI / nSides; // Distance from center to each of the vertices float d = (float) (r / Math.cos(halfAngleIncRad)); // Initialization of the vector used to calculate each vertex. Vector2 centerToVertex = new Vector2(); centerToVertex.set(0, d); centerToVertex.rotateRad((float) halfAngleIncRad); for (int i = 0; i < nSides; i++) { // Calculate vertex vertices[2 * i] = cx + centerToVertex.x; vertices[2 * i + 1] = cy + centerToVertex.y; // Rotate for the next vertex centerToVertex.rotate(angleInc); } polygon.setVertices(vertices); return polygon; }
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;/*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:magory.svg.Sovery.java
public void loadElement(Element el, float[] matrixOld) { String elname = el.getName(); if (elname.equals("svg")) getSVGDimentions(el);/*from ww w . j a v a 2 s.c o m*/ int count = el.getChildCount(); // magic for transforms and matrixes, don't touch unless you know what you are doing String trans = getAttribute(el, "transform", "", false); String title = getTitle(el); float elementX = getFloat(el.getAttribute("x", "0")); float elementY = getFloat(el.getAttribute("y", "0")); float elementWidth = getFloat(getAttribute(el, "width", "", false)); float elementHeight = getFloat(getAttribute(el, "height", "", false)); Vector2 origin = new Vector2(elementWidth / 2, elementHeight / 2); Vector2 scale = new Vector2(1, 1); Vector2 scaleOld = new Vector2(1, 1); Vector2 translate = new Vector2(); float rr; // rotation Matrix3 matrix = getTransformMatrix(trans); float oldR = 0; if (matrixOld != null) // is a matrix { Matrix3 mOld = new Matrix3(matrixOld); oldR = mOld.getRotation(); getScale(mOld, scaleOld); if (scaleOld.y < 0 || scaleOld.x < 0) { origin.rotate(oldR); matrix.mulLeft(translate(-origin.x, -origin.y)); origin.rotate(-oldR); matrix.mulLeft(mOld); matrix.mul(translate(elementX, elementY)); matrix.translate(origin.x, origin.y); } else { origin.rotate(-oldR); matrix.mulLeft(translate(-origin.x, -origin.y)); origin.rotate(oldR); matrix.mulLeft(mOld); matrix.mul(translate(elementX, elementY)); matrix.translate(origin.x, origin.y); } } else { matrix.mulLeft(translate(-origin.x, -origin.y)); matrix.mul(translate(elementX, elementY)); matrix.translate(origin.x, origin.y); } if (count != 0) for (int i = 0; i < count; i++) loadElement(el.getChild(i), matrix.getValues()); // important magic for width,height and x,y // inspired by this: http://stackoverflow.com/questions/16359246/how-to-extract-position-rotation-and-scale-from-matrix-svg // and this: http://www.w3.org/TR/css3-transforms/ matrix.getScale(scale); rr = matrix.getRotation(); // magic which I don't understand getScale(matrix, scale); if (scale.y < 0 && scaleOld.y > 0) { Vector2 det = new Vector2(0, elementHeight * Math.signum(scale.y) * 2); // because y flip uses top border of the image det.rotate(rr); matrix.translate(det); } if (scaleOld.y < 0 || scaleOld.x < 0) { Vector2 det = new Vector2(0, scaleOld.y * elementHeight / scale.y); // because... well, I don't know why if (scale.y < 0) det.rotate(rr + 180); else if (scale.x < 0) det.rotate(rr); else { if (scaleOld.x < 0) det.rotate(-rr + 180); else det.rotate(-rr); } matrix.translate(det); } matrix.getTranslation(translate); float width = elementWidth * scale.x; float height = elementHeight * scale.y; float yyy = SVGHeight - translate.y - height; float xxx = translate.x; if (title.startsWith("testing")) { Gdx.app.log("test", "oldR:" + oldR + " sx:" + scaleOld.x + " sy:" + scaleOld.y); Gdx.app.log("test", ":::" + title + ":" + xxx + "," + yyy + ":" + rr + " " + width + "x" + height + " rr:" + rr + " scalex:" + scale.x + " scaley:" + scale.y); } rr = -rr; if (width < 0) rr = rr + 180; if (rr < 0) rr += 360; if (title.startsWith("testing")) Gdx.app.log("test", ":::newrr:" + rr); if (elname.equals("path")) // path { String d = el.getAttribute("d", ""); newPath(parsePathToArray(d, elementX, elementY, SVGHeight), el, title); } else if (isText(elname)) // text { Element e = getChild(el, "tspan"); if (e == null) return; String text; if (e.getText() == null) text = ""; else text = e.getText().trim(); // font-size as height! - width not set unfortunately // example: font-size:44.03109741px; String style = getAttribute(el, "style", "", false); String styles[] = style.split("\\;"); Color color = new Color(1, 1, 1, 1); if (styles != null && styles.length > 0) { for (int i = 0; i < styles.length; i++) { if (isStyle(styles[i], "font-size")) { String stylesdata[] = styles[i].split("\\:"); stylesdata[1] = stylesdata[1].replace("px", ""); stylesdata[1] = stylesdata[1].replace(";", ""); height = getFloat(stylesdata[1].trim()); } else if (isStyle(styles[i], "fill")) { //fill:#effffa String stylesdata[] = styles[i].split("\\:"); stylesdata[1] = stylesdata[1].replace("#", ""); stylesdata[1] = stylesdata[1].replace(";", ""); color = getColorFromString(stylesdata[1].trim()); } } } newText(text, el, xxx, yyy, width, height, rr, color); } else if (isImage(elname)) // obraz { String name = getImageName(getAttribute(el, "xlink:href", "", false)); newImage(name, el, xxx, yyy, width, height, rr); } else if (isRect(elname)) // obraz { Element title2 = getChild(el, "title"); if (title2 != null) newRect(title2.getText(), el, xxx, yyy, width, height, rr); else newRect("", el, xxx, yyy, width, height, rr); } }
From source file:releasethekraken.entity.projectile.EntityWaterBomb.java
@Override public void onImpact() { final int bombDamage = this.damage; final GameWorld bombWorld = this.world; final Vector2 bombPos = this.physBody.getPosition().cpy(); final Entity bombOwner = this.owner; //TODO: This could be effected by the same bug as Issue #91. //"Splash" with some water squirts! this.world.addSpawnTask(new GameWorld.BodySpawnTask() { @Override/*from w ww. j a v a2 s . co m*/ protected void doTask() { int splashes = 12; Vector2 splashVel = new Vector2(200, 0); for (int i = 0; i < splashes; i++) { int damage = (int) (bombDamage / 25F); //Calculate damage based on bomb damage new EntityWaterSquirt(bombWorld, bombPos.x, bombPos.y, splashVel.x, splashVel.y, bombOwner, damage, 30); //Short despawn time splashVel.rotate(((float) splashes / (i + 1)) * 360); } } }); super.onImpact(); }
From source file:releasethekraken.entity.seacreature.EntityPlayer.java
@Override public void attack(int damage) { Vector2 velocity = this.aimPos.cpy().sub(this.getPos()).nor().scl(500); //Calculate direction and velocity to fire at float spread = 10F; //The amount of possible spread, in degrees velocity.rotate(this.world.random.nextFloat() * spread - spread / 2); //Add +- spread/2 degrees of spread EntitySeaShell projectile = new EntitySeaShell(this.world, this.getPos().x, this.getPos().y, velocity.x, velocity.y, this, damage); projectile.getPhysBody().applyAngularImpulse(this.world.random.nextFloat() * 50 - 25, true); //Randomly spin it a bit }
From source file:us.thirdmillenium.strategicassaultsimulator.agents.ConeAgent.java
License:Apache License
/** * Computes distance and what is seen for each degree of viewing angle. * *///from ww w. j a v a2 s. c o m private double[] computeVision() { double[] item = new double[this.degreesOfView]; double[] distance = new double[this.degreesOfView]; float startDeg = this.rotation + (this.degreesOfView / 2); float degree = 0; // Store the first point for the vision Polygon this.visionPolygonVertices[0] = this.position.x; this.visionPolygonVertices[1] = this.position.y; // Consider every degree angle coming from Agent for (int i = 0; i < this.degreesOfView; i++) { // Set values for this degree and arrays degree = startDeg - i; item[i] = Params.ConeVisEmpty; distance[i] = this.visionDepth; // Variables to hold intermediate calcs Vector2 intersection = new Vector2(); float distToObject; boolean seenAgent = false; // Calculate the direction for the Agent at this angle degree Vector2 direction = new Vector2(0, 1); direction.rotate(degree); // Calculate the furthest point Agent can see for this degree Vector2 endPoint = this.position.cpy(); endPoint.mulAdd(direction, this.visionDepth); // The boundRect is used for Sprite collision calcs //Rectangle agentBoundRect = new Rectangle(0, 0, Params.AgentTileSize, Params.AgentTileSize); //Rectangle bulletBoundRect = new Rectangle(0, 0, 5, 8); // Hard coded!!! Gah!! // Detect Bullets? // Detect Enemy Agents Iterator<AgentModel> enemyItr = this.enemyTracker.iterator(); AgentModel enemy; while (enemyItr.hasNext()) { enemy = enemyItr.next(); // If segment intersects circle if (Intersector.intersectSegmentCircle(this.position, endPoint, enemy.getPosition(), Params.AgentRadiusSquared)) { distToObject = this.position.dst(enemy.getPosition()) - (Params.AgentTileSize / 2.2f); // Check if Agents are within Vision Depth if (distToObject < distance[i]) { item[i] = Params.ConeVisEnemy; distance[i] = distToObject; seenAgent = true; } } } // Detect Friendly Agents Iterator<AgentModel> teamItr = this.teamTracker.iterator(); AgentModel team; while (teamItr.hasNext()) { team = teamItr.next(); // If segment intersects circle if (team != this && Intersector.intersectSegmentCircle(this.position, endPoint, team.getPosition(), Params.AgentRadiusSquared)) { distToObject = this.position.dst(team.getPosition()) - (Params.AgentTileSize / 2); // Check if Agents are within Vision Depth if (distToObject < distance[i]) { item[i] = Params.ConeVisTeam; distance[i] = distToObject; seenAgent = true; } } } // Detect Collision with Walls or Boundary Iterator<Line> lineItr = this.collisionLines.iterator(); Line line; while (lineItr.hasNext()) { line = lineItr.next(); if (Intersector.intersectSegments(this.position, endPoint, line.start, line.end, intersection)) { distToObject = intersection.dst(this.position); if (distToObject < distance[i]) { item[i] = Params.ConeVisWall; distance[i] = distToObject; seenAgent = false; // if true, then Agent on other side of wall } } } // Detect Path ONLY when an Agent hasn't been seen on this degree line. if (!seenAgent) { TileNode node; for (int index = this.preferredPathIndex; index < this.preferredPath.getCount(); index++) { node = this.preferredPath.get(index); // Place radius 5 circle over preferred path node if (Intersector.intersectSegmentCircle(this.position, endPoint, node.getPixelVector2(), 25)) { distToObject = this.position.dst(node.getPixelVector2()); // Check if Agents are within Vision Depth if (distToObject < distance[i]) { item[i] = Params.ConeVisPath; distance[i] = distToObject; } } } } // Store the x,y point for this degree line this.visionPolygonVertices[2 + (i * 2)] = this.position.x + (direction.x * (float) distance[i]); this.visionPolygonVertices[3 + (i * 2)] = this.position.y + (direction.y * (float) distance[i]); // Normalize distance to (agent edge -> 1) if (distance[i] < Params.AgentCircleRadius) { distance[i] = Params.AgentCircleRadius; } distance[i] = distance[i] / (float) this.visionDepth; } return GraphicsHelpers.interleaveDoubleArrays(item, distance); }
From source file:us.thirdmillenium.strategicassaultsimulator.agents.ConePuppetAgent.java
License:Apache License
/** * Computes distance and what is seen for each degree of viewing angle. * *//*from www.j a v a2 s . co m*/ //private double[] computeVision() { private void computeVision() { double[] item = new double[this.degreesOfView]; double[] distance = new double[this.degreesOfView]; float startDeg = this.rotation + (this.degreesOfView / 2); float degree = 0; boolean seenEnemyAgent = false; float degreeSeenEnemyAgent = -1; // Store the first point for the vision Polygon this.visionPolygonVertices[0] = this.position.x; this.visionPolygonVertices[1] = this.position.y; // Consider every degree angle coming from Agent for (int i = 0; i < this.degreesOfView; i++) { // Set values for this degree and arrays degree = startDeg - i; item[i] = Params.ConeVisEmpty; distance[i] = this.visionDepth; // Variables to hold intermediate calcs Vector2 intersection = new Vector2(); float distToObject; boolean seenAgent = false; // Calculate the direction for the Agent at this angle degree Vector2 direction = new Vector2(0, 1); direction.rotate(degree); // Calculate the furthest point Agent can see for this degree Vector2 endPoint = this.position.cpy(); endPoint.mulAdd(direction, this.visionDepth); // The boundRect is used for Sprite collision calcs //Rectangle agentBoundRect = new Rectangle(0, 0, Params.AgentTileSize, Params.AgentTileSize); //Rectangle bulletBoundRect = new Rectangle(0, 0, 5, 8); // Hard coded!!! Gah!! // Detect Bullets? // Detect Enemy Agents Iterator<AgentModel> enemyItr = this.enemyTracker.iterator(); AgentModel enemy; while (enemyItr.hasNext()) { enemy = enemyItr.next(); // If segment intersects circle if (Intersector.intersectSegmentCircle(this.position, endPoint, enemy.getPosition(), Params.AgentRadiusSquared)) { distToObject = this.position.dst(enemy.getPosition()) - (Params.AgentTileSize / 2.2f); // Check if Agents are within Vision Depth if (distToObject < distance[i]) { item[i] = Params.ConeVisEnemy; distance[i] = distToObject; seenAgent = true; seenEnemyAgent = true; degreeSeenEnemyAgent = degree; } } } // Detect Friendly Agents Iterator<AgentModel> teamItr = this.teamTracker.iterator(); AgentModel team; while (teamItr.hasNext()) { team = teamItr.next(); // If segment intersects circle if (team != this && Intersector.intersectSegmentCircle(this.position, endPoint, team.getPosition(), Params.AgentRadiusSquared)) { distToObject = this.position.dst(team.getPosition()) - (Params.AgentTileSize / 2); // Check if Agents are within Vision Depth if (distToObject < distance[i]) { item[i] = Params.ConeVisTeam; distance[i] = distToObject; seenAgent = true; } } } // Detect Collision with Walls or Boundary Iterator<Line> lineItr = this.collisionLines.iterator(); Line line; while (lineItr.hasNext()) { line = lineItr.next(); if (Intersector.intersectSegments(this.position, endPoint, line.start, line.end, intersection)) { distToObject = intersection.dst(this.position); //float tempAngle = this.position.angle(intersection); if (distToObject < distance[i]) { item[i] = Params.ConeVisWall; distance[i] = distToObject; seenAgent = false; // if true, then Agent on other side of wall } } } // Detect Path ONLY when an Agent hasn't been seen on this degree line. if (!seenAgent) { TileNode node; for (int index = this.preferredPathIndex; index < this.preferredPath.getCount(); index++) { node = this.preferredPath.get(index); // Place radius 5 circle over preferred path node if (Intersector.intersectSegmentCircle(this.position, endPoint, node.getPixelVector2(), 25)) { distToObject = this.position.dst(node.getPixelVector2()); // Check if Agents are within Vision Depth if (distToObject < distance[i]) { item[i] = Params.ConeVisPath; distance[i] = distToObject; } } } } // Store the x,y point for this degree line this.visionPolygonVertices[2 + (i * 2)] = this.position.x + (direction.x * (float) distance[i]); this.visionPolygonVertices[3 + (i * 2)] = this.position.y + (direction.y * (float) distance[i]); // Normalize distance to (agent edge -> 1) if (distance[i] < Params.AgentCircleRadius) { distance[i] = Params.AgentCircleRadius; } distance[i] = distance[i] / (float) this.visionDepth; } //return GraphicsHelpers.interleaveDoubleArrays(item, distance); this.input = GraphicsHelpers.interleaveDoubleArrays(item, distance); this.output = new double[3]; // Check Danger Information if ((this.dangerCoolDown--) < 1) { this.dangerOverride = false; } // Update Position if (this.dangerOverride && !seenEnemyAgent) { // Being shot and don't see enemy Agent this.output[0] = 0.5; // no rotate this.output[1] = 1; // Move fast as hell this.output[2] = 0; // Don't shoot } else { puppetCrunch(seenEnemyAgent, degreeSeenEnemyAgent, distance, item); } }