@Override public boolean update(double timeDelta) { Vector2f moveDelta = new Vector2f(getVelocity()); moveDelta.scale((float) timeDelta); Vector2f.add(getPosition(), moveDelta, getPosition()); if (Math.abs(getPosition().x) > halfRangeX || Math.abs(getPosition().y) > halfRangeY) return true; return false; }
private void onGameStatePlaying() { // ball Point position = ball.getPosition(); if (shadowCount >= SHADOW_SKIP) { if (previousBallPositions.size() >= NUMBER_OF_BALL_SHADOWS) { previousBallPositions.removeLast(); } previousBallPositions.addFirst(new Point(position)); shadowCount = 0; } else { shadowCount += 1; } position.add((ballSpeed * ballUnitVector.getX()), -(ballSpeed * ballUnitVector.getY())); ball.setPosition(position); ball.setVisible(true); for (int i = 0; i < NUMBER_OF_BALL_SHADOWS; i++) { VisualControl visualControl = ballShadows.get(i); if (previousBallPositions.size() > i) { visualControl.setPosition(previousBallPositions.get(i)); visualControl.setVisible(true); } else { visualControl.setVisible(false); } } // bounce if (bouncedControl != null) { if (!bouncedControl.isHit(ball.getPosition())) { bouncedControl = null; } } else { for (BounceableControl bounceableControl : paddles.values()) { bounceableControls.add(bounceableControl); } for (BounceableControl bounceableControl : bounceableControls) { if (bounceBall(bounceableControl)) { bouncedControl = bounceableControl; break; } } for (BounceableControl bounceableControl : paddles.values()) { bounceableControls.remove(bounceableControl); } } // goal if ((position.getX() <= 0.0f) || (position.getX() >= (float) displayMode.getWidth())) { gameState = GameState.End; } }
/** * Performs a gun shot and deals damage if necessary * * @param player the player who is shooting * @param intersectionInfoList any intersections along the bullet path */ public void handleGunShot(Player player, ArrayList<EntityIntersectionInfo> intersectionInfoList) { if (intersectionInfoList != null) { // Find nearest intersection to the player Entity nearestIntersectingEntity = null; float nearestIntersectionDistance = 0.0f; for (EntityIntersectionInfo info : intersectionInfoList) { // Ignore intersections with players on your team if (info.getEntity() instanceof Player) { Player _player = (Player) info.getEntity(); if (player.getTeam().getID() == _player.getTeam().getID()) continue; } // Check intersection points for (Vector2f p : info.getIntersectionPoints()) { // Calculate distance between intersection point and player Vector2f dif = new Vector2f(); Vector2f.sub(player.getPosition(), p, dif); float len = dif.length(); // Update nearest intersection entity if (nearestIntersectionDistance == 0.0f || len < nearestIntersectionDistance) { nearestIntersectionDistance = len; nearestIntersectingEntity = info.getEntity(); } } } // Check if nearest intersecting entity is player and do damage if so if (nearestIntersectingEntity != null) { if (nearestIntersectingEntity instanceof Player) { Player hitPlayer = (Player) nearestIntersectingEntity; // System.out.println("hit player"); if (hitPlayer.getTeam().getID() != player.getTeam().getID()) { // TODO: move damage into method or constant hitPlayer.doDamage(player.getWeaponDamage()); } } } } }
// Depending on the degrees at which this projectile was fired, the X and Y speeds can // be calculated using math... private void calculateSpeed(float degrees) { // Using simple trigonometry we can calculate the sides of a triangle by given (shooting) angel // and // the length of the hypotenuse, which we will keep as 1 for simplicity's sake // sin(a) = opposite / hypotenuse // cos(a) = adjacent / hypotenuse // -> lengths of the opposites and adjacent sides can be calculated by using the following // formula // (Hypotenuse is 1, so we can disregard it completely) // opposite = sin(a) / 1 // adjacent = cos(a) / 1 speed.x = (float) Math.cos(Math.toRadians(degrees)) * 20; speed.y = (float) Math.sin(Math.toRadians(degrees)) * 20; }
private void setupViewMatrix(boolean reverseY) { viewMatrix = new Matrix4f(); Matrix4f.rotate( (reverseY ? -1 : 1) * cameraAngle.getY(), new Vector3f(1, 0, 0), viewMatrix, viewMatrix); Matrix4f.rotate(cameraAngle.getX(), new Vector3f(0, 1, 0), viewMatrix, viewMatrix); Matrix4f.translate( reverseY ? new Vector3f(cameraPos.getX(), -cameraPos.getY(), cameraPos.getZ()) : cameraPos, viewMatrix, viewMatrix); }
private void calculateOrigin(int x, int y, float degrees) { // this is the middle point of the tank (and turret) from where the projectile was shot // since the projectile has to originate from the end of the turret and not the middle // point, we can calculate its actual starting position by knowing the angle (degrees) // and the size of the tank (radius of drawing circle) which is 150 // Note: The hypotenuse is equal to the radius of the drawing circle, which is 150 // -> Delta Y is then defined by sin(degrees) = opposite / 150 // -> opposite = sin(degrees)*150 (and we need to add 150 because the drawing circle // originates from the screen's 0/0 and not the middle of the circle) // Delta X is the same as above, but with using cos(degrees) instead // we use 175 here to account for drawing over the turret, which we dont want to do position.x = x + (float) Math.cos(Math.toRadians(degrees)) * 175 + 150; position.y = y + (float) Math.sin(Math.toRadians(degrees)) * 175 + 150; }
public boolean equals(Object obj) { if (!obj.getClass().getName().endsWith("Vertex")) { return false; } Vertex otherVert = (Vertex) obj; // Compare position Vector3f otherPos = otherVert.getPosition(); if (position.getX() != otherPos.getX()) { return false; } if (position.getY() != otherPos.getY()) { return false; } if (position.getZ() != otherPos.getZ()) { return false; } // Compare Unwrap Vector2f otherUnwrap = otherVert.getUnwrap(); if (unwrap.getX() != otherUnwrap.getX()) { return false; } if (unwrap.getY() != otherUnwrap.getY()) { return false; } // Compare Normal boolean hasNormal = hasNormal(); boolean otherHasNormal = otherVert.hasNormal(); if (hasNormal != otherHasNormal) { return false; } // One has normal, the other one doesn't if (hasNormal == false) { return true; } // Since both are same, both don't have a normal Vector3f otherNormal = otherVert.getNormal(); if (normal.getX() != otherNormal.getX()) { return false; } if (normal.getY() != otherNormal.getY()) { return false; } if (normal.getZ() != otherNormal.getZ()) { return false; } // All clear return true; }
/** Convenience accessor */ public Vector2f getOffset(Vector2f ret) { if (ret == null) { ret = new Vector2f(ox, oy); } else { ret.set(ox, oy); } return ret; }
/** Convenience accessor */ public Vector2f getLocation(Vector2f ret) { if (ret == null) { ret = new Vector2f(x, y); } else { ret.set(x, y); } return ret; }
private void onGameStateStart() { wonControl.setVisible(false); lostControl.setVisible(false); Random random = new Random(new Date().getTime()); float ballAngle = (float) random.nextInt(360); float ballX = (float) Math.cos(Math.toRadians(ballAngle)); float ballY = (float) Math.sin(Math.toRadians(ballAngle)); if (ballX == 0.0f) { ballX = 0.5f; } if (ballY == 0.0f) { ballY = 0.5f; } log.debug("angle: " + ballAngle + ", x: " + ballX + ", y: " + ballY); ballUnitVector.set(ballX, ballY); ballUnitVector = ballUnitVector.normalise(null); gameState = GameState.Playing; }
/** * Attempts to add an image to this {@link GLTexture} * * @param image The {@link Image} to add * @return The resulting {@link Texture}, or <code>null</code> if it didn't fit */ public Texture addImage(Image image) { assert image.format == format; RectanglePacker.Rectangle rpr = packer.insert(image.getWidth(), image.getHeight(), image); if (rpr != null) { assert rpr.width == image.getWidth(); assert rpr.height == image.getHeight(); writeToTexture(rpr, image.getData()); Vector2f bottomleft = new Vector2f(rpr.x, rpr.y); Vector2f topRight = new Vector2f(rpr.x + rpr.width, rpr.y + rpr.height); bottomleft.x /= size.getWidth(); bottomleft.y /= size.getHeight(); topRight.x /= size.getWidth(); topRight.y /= size.getHeight(); Texture t = new Texture(this, bottomleft, topRight, image); residentTextures.add(t); return t; } else { return null; } }
@Override public void advance(float amount) { if (!missile.getSource().isAlive()) { IceUtils.destroy(missile); return; } super.advance(amount); weaponCooldown = Math.max(0, weaponCooldown - amount); if (target == null) return; Vector2f.add(destOffset, target.getLocation(), dest); accelerate(); turnToward(dest); if (ammo > 0 && weaponCooldown == 0) { CombatEntityAPI nearest = null; float record = Float.MAX_VALUE; for (int i = 0; i < potentialTargets.size(); ++i) { CombatEntityAPI m = (CombatEntityAPI) potentialTargets.get(i); float dist2 = MathUtils.getDistanceSquared(missile, m); if (dist2 < record && dist2 <= WEAPON_RANGE_SQUARED) { record = dist2; nearest = m; } } if (nearest != null) { Global.getCombatEngine() .spawnProjectile( missile.getSource(), null, WEAPON_ID, missile.getLocation(), VectorUtils.getAngle(missile.getLocation(), nearest.getLocation()), new Vector2f()); --ammo; weaponCooldown = WEAPON_COOLDOWN; } } }
private Vector2f converttoimagesizes( Vector2f oldvec, Vector2f offset, BufferedImage oldimage, BufferedImage newimage) { Vector2f vec = new Vector2f(); vec.x = oldvec.x * oldimage.getWidth(); vec.x += offset.x; vec.x /= newimage.getWidth(); vec.y = oldvec.y * oldimage.getHeight(); vec.y += offset.y; vec.y /= newimage.getHeight(); return vec; }
@Override public void evaluateCircumstances() { super.evaluateCircumstances(); // if(target == null || (!(target instanceof ShipAPI) || !((ShipAPI)target).isAlive())) { // findTarget(); // return; // } Vector2f.sub( MathUtils.getRandomPointInCircle(target.getLocation(), target.getCollisionRadius()), target.getLocation(), destOffset); if (missile.isFading() || ammo <= 0 || !missile.getSource().isAlive()) IceUtils.destroy(missile); potentialTargets.clear(); potentialTargets.addAll(AIUtils.getNearbyEnemyMissiles(missile, POTENTIAL_TARGET_RANGE)); potentialTargets.addAll(AIUtils.getNearbyEnemies(missile, POTENTIAL_TARGET_RANGE)); }
private boolean bounceBall(BounceableControl control) { /* log.debug("Cheking..."); log.debug("\tcontrol: "+control.getPosition().toString()+", ball: "+ball.getPosition().toString()); log.debug("\tvector: x="+ballUnitVector.getX()+", y="+ballUnitVector.getY()); */ boolean isHit = false; if ((control.isVisible()) && (control.isHit(ball.getPosition()))) { log.debug("bounced!!!!!!!!!!!!!!"); float angleDelta = 90.0f - control.getRotation(); // get current angle of ball vector Point previousBallPosition = new Point(0.0f, 0.0f); Point currentBallPosition = new Point(ballUnitVector.getX(), ballUnitVector.getY()); // float ballVectorMagnitude = PointUtility.getDistance(previousBallPosition, // currentBallPosition); float currentBallAngle = PointUtility.getAngle(previousBallPosition, currentBallPosition); log.debug("\t\tcurrentBallAngle=" + currentBallAngle); // get new vector float targetBallAngle = (currentBallAngle + angleDelta); float newX = (float) Math.cos(Math.toRadians(targetBallAngle)); float newY = (float) Math.sin(Math.toRadians(targetBallAngle)); log.debug("\t\tnew vector: x=" + newX + ", y=" + newY); newX = (-1 * newX); // back to original angle previousBallPosition.set(0.0f, 0.0f); currentBallPosition.set(newX, newY); log.debug("\t\tnewX=" + newX + ", newY=" + newY); float newAngle = PointUtility.getAngle(previousBallPosition, currentBallPosition); targetBallAngle = (newAngle - angleDelta); log.debug("\t\tnew angle=" + newAngle + ", targetBallAngle=" + targetBallAngle); newX = (float) Math.cos(Math.toRadians(targetBallAngle)); newY = (float) Math.sin(Math.toRadians(targetBallAngle)); ballUnitVector.set(newX, newY); ballUnitVector = ballUnitVector.normalise(null); log.debug("\t\tfinal: x=" + ballUnitVector.getX() + ", y=" + ballUnitVector.getY()); isHit = true; } return isHit; }
/** * Get the distance to a coordinate * * @param xx * @param yy * @return distance, in pixels */ public float getDistanceTo(float xx, float yy) { return Vector2f.sub(new Vector2f(xx, yy), new Vector2f(getX(), getY()), null).length(); }
/** * Get the distance to another entity * * @param xx * @param yy * @return distance, in pixels */ public float getDistanceTo(Entity e) { return Vector2f.sub(new Vector2f(e.getX(), e.getY()), new Vector2f(getX(), getY()), null) .length(); }
public void move(float scale) { Vector2f oldPosition = new Vector2f(position); // make our move position.y += velocity.y * scale; // figure our new bounds BoundingBox box = getBoundingBox(); // check for floor collision int y = (int) Math.floor(box.bottomY); for (int x = (int) Math.floor(box.leftX); x < Math.ceil(box.rightX); x++) { TileMapTile tile = null; try { tile = map.getMap()[x][y]; } catch (Exception e) { } if (tile != null && velocity.y <= 0) { WalkingEntity walker = this instanceof WalkingEntity ? (WalkingEntity) this : null; if (walker != null && !walker.dead && tile.isDangerous()) { ((WalkingEntity) this).damage(5); position.y = (int) oldPosition.y; velocity.y = 15f; velocity.x = -0.5f * velocity.x; break; } if (tile.isSolid() || tile.isPlatform()) { if (velocity.y < -1) { floorCollision(); System.out.println(this.getClass().getSimpleName() + ": " + box + " " + this.position); } position.y = (int) oldPosition.y; velocity.y = 0f; // apply friction if (Math.abs(velocity.x) > 0) { float sign = Math.abs(velocity.x) / velocity.x; velocity.x -= sign * 9.8 * scale; // if we managed to reverse the direction of the horiz velocity, just stop if (velocity.x != 0 && sign != Math.abs(velocity.x) / velocity.x) { velocity.x = 0; } } break; } } } position.x += velocity.x * scale; // figure our new bounds box = getBoundingBox(); // check for wall collision for (int x = (int) box.leftX; x <= box.rightX; x++) { for (y = (int) box.bottomY; y < box.topY; y++) { TileMapTile tile = null; try { tile = map.getMap()[x][y]; } catch (Exception e) { } if (tile != null && tile.isSolid()) { wallCollision(); // System.out.print(" WALL [" + x + ", " + y + "]"); if (velocity.x > 0) position.x = (int) Math.ceil(oldPosition.x); else position.x = (int) Math.floor(oldPosition.x); velocity.x = 0f; break; } } } }
public Vector2f getUnwrap() { return new Vector2f(unwrap.getX(), unwrap.getY()); }
public float[] getUVW() { return new float[] {unwrap.getX(), unwrap.getY(), 0f}; }
public void applyGravity(float scale) { velocity.y -= 9.8 * 4 * scale; if (velocity.y < TERMINAL_VELOCITY) velocity.y = TERMINAL_VELOCITY; }
public static Vector2f add(Vector2f v1, Vector2f v2) { return Vector2f.add(v1, v2, v1); }
public static void normalize(Vector2f vector) { try { vector.normalise(); } catch (Exception ignored) { } }
public static void truncate(Vector2f vector, float max) { float length = vector.length(); if (length == 0) return; float i = max / length; vector.scale(i < 1. ? 1.f : i); }
@Override public void update(BaseObject parent) { Vector2f acceleration = ((GameObject) parent).getAcceleration(); acceleration.set(0, 0); if (sys.keyboard.isKeyPressed(ButtonActions.MOVE_UP)) { acceleration.y = ACCELERATION; } if (sys.keyboard.isKeyPressed(ButtonActions.MOVE_DOWN)) { acceleration.y = -ACCELERATION; } if (sys.keyboard.isKeyPressed(ButtonActions.MOVE_LEFT)) { acceleration.x = -ACCELERATION; } if (sys.keyboard.isKeyPressed(ButtonActions.MOVE_RIGHT)) { acceleration.x = ACCELERATION; } if (sys.currentTime - lastTime < fireRate) { return; } // FIXME I really shouldn't be using hardcoded values to figure out where to // shoot the bullets from. // FIXME I also REALLY REALLY need to get my vectors sorted out so that I don't have to // resort to this ugliness. bulletVelocity.set( ((GameObject) parent).getVelocity().x, ((GameObject) parent).getVelocity().x); bulletPosition.set(16f, 0f); if (sys.keyboard.isKeyPressed(ButtonActions.FIRE_LEFT)) { bulletVelocity.x -= BULLET_VELOCITY; bulletPosition.y = 16f; bulletPosition.x = 0f; } if (sys.keyboard.isKeyPressed(ButtonActions.FIRE_RIGHT)) { bulletVelocity.x += BULLET_VELOCITY; bulletPosition.y = 16f; bulletPosition.x = 32f; } if (sys.keyboard.isKeyPressed(ButtonActions.FIRE_UP)) { bulletVelocity.y += BULLET_VELOCITY; bulletPosition.y = 32f; } if (sys.keyboard.isKeyPressed(ButtonActions.FIRE_DOWN)) { bulletVelocity.y -= BULLET_VELOCITY; bulletPosition.y = 0f; } if (bulletVelocity.x != 0f || bulletVelocity.y != 0f) { Vector2f position = ((GameObject) parent).getPosition(); bulletPosition.x += position.x; bulletPosition.y += position.y; GameObject bullet = bulletPool.obtain(); if (bullet != null) { bullet.setPosition(bulletPosition.x, bulletPosition.y); bulletVelocity.rotate(bulletCounter * spreadDegree); bullet.setVelocity(bulletVelocity.x, bulletVelocity.y); sys.manager.add(bullet); if (bulletCounter == spreadCount / 2) { bulletCounter = -bulletCounter; } else { bulletCounter++; } } } lastTime = sys.currentTime; }
public void setUV(float[] uv) { unwrap.x = uv[0]; unwrap.y = uv[1]; }
private void update() { float posDelta = 0.1f; if (Keyboard.isKeyDown(Keyboard.KEY_W)) { Vector3f.add( cameraPos, new Vector3f( (float) (Math.cos(cameraAngle.getX() + Math.PI / 2) * posDelta), 0, (float) (Math.sin(cameraAngle.getX() + Math.PI / 2) * posDelta)), cameraPos); } if (Keyboard.isKeyDown(Keyboard.KEY_D)) { Vector3f.add( cameraPos, new Vector3f( (float) (Math.cos(cameraAngle.getX() + Math.PI) * posDelta), 0, (float) (Math.sin(cameraAngle.getX() + Math.PI) * posDelta)), cameraPos); } if (Keyboard.isKeyDown(Keyboard.KEY_S)) { Vector3f.add( cameraPos, new Vector3f( (float) (Math.cos(cameraAngle.getX() + Math.PI * 3 / 2) * posDelta), 0, (float) (Math.sin(cameraAngle.getX() + Math.PI * 3 / 2) * posDelta)), cameraPos); } if (Keyboard.isKeyDown(Keyboard.KEY_A)) { Vector3f.add( cameraPos, new Vector3f( (float) (Math.cos(cameraAngle.getX()) * posDelta), 0, (float) (Math.sin(cameraAngle.getX()) * posDelta)), cameraPos); } if (Keyboard.isKeyDown(Keyboard.KEY_Q)) { Vector3f.add(cameraPos, new Vector3f(0, -1, 0), cameraPos); } if (Keyboard.isKeyDown(Keyboard.KEY_E)) { Vector3f.add(cameraPos, new Vector3f(0, 1, 0), cameraPos); } if (Keyboard.isKeyDown(Keyboard.KEY_R)) { Vector3f.add(modelAngle, new Vector3f(0, 0.05f, 0), modelAngle); } if (Keyboard.isKeyDown(Keyboard.KEY_UP)) { Vector3f.add(modelPos, new Vector3f(0.1f, 0, 0), modelPos); } if (Keyboard.isKeyDown(Keyboard.KEY_DOWN)) { Vector3f.add(modelPos, new Vector3f(-0.1f, 0, 0), modelPos); } Vector2f.add(cameraAngle, new Vector2f(Mouse.getDX() * 0.004f, 0), cameraAngle); Vector2f.add(cameraAngle, new Vector2f(0, -Mouse.getDY() * 0.004f), cameraAngle); if (cameraAngle.getY() > Math.PI / 2) cameraAngle.setY((float) Math.PI / 2); if (cameraAngle.getY() < -Math.PI / 2) cameraAngle.setY((float) -Math.PI / 2); }
public void update() { position.x += speed.x; position.y += speed.y; }