com.badlogic.gdx.math.Vector3 Java Examples
The following examples show how to use
com.badlogic.gdx.math.Vector3.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: GameEngine.java From GdxDemo3D with Apache License 2.0 | 6 votes |
public Entity rayTest(Ray ray, Vector3 hitPointWorld, short belongsToFlag, short collidesWithFlag, float rayDistance, Bits layers) { rayFrom.set(ray.origin); rayTo.set(ray.direction).scl(rayDistance).add(rayFrom); callback.setCollisionObject(null); callback.setClosestHitFraction(1f); callback.setRay(ray, rayDistance); callback.setLayers(layers); callback.setCollisionFilterMask(belongsToFlag); callback.setCollisionFilterGroup(collidesWithFlag); dynamicsWorld.rayTest(rayFrom, rayTo, callback); if (callback.hasHit()) { if (hitPointWorld != null) { callback.getHitPointWorld(hitPointWorld); } long entityId = callback.getCollisionObject().getUserPointer(); return getEntity(entityId); } return null; }
Example #2
Source File: LevelScreen.java From FruitCatcher with Apache License 2.0 | 6 votes |
@Override public boolean touchUp(int screenX, int screenY, int pointer, int button) { Vector3 touchPos = new Vector3(); touchPos.set(screenX, screenY, 0); camera.unproject(touchPos); for(int i=0;i<buttons.length;i++) { if (buttons[i].isPressed(touchPos)) { Gdx.app.log(TAG, "Button " + (i+1) + " pressed"); if (i < 3 && isLevelUnlocked[i]) { game.startGame(i); game.gotoGameScreen(null); } else if (i == 3) { game.gotoMenuScreen(); } break; } } return true; }
Example #3
Source File: BulletFollowPathTest.java From gdx-ai with Apache License 2.0 | 6 votes |
/** Creates a random path which is bound by rectangle described by the min/max values */ private static Array<Vector3> createRandomPath (int numWaypoints, float minX, float minY, float maxX, float maxY, float height) { Array<Vector3> wayPoints = new Array<Vector3>(); float midX = (maxX + minX) / 2f; float midY = (maxY + minY) / 2f; float smaller = Math.min(midX, midY); float spacing = MathUtils.PI2 / numWaypoints; for (int i = 0; i < numWaypoints; i++) { float radialDist = MathUtils.random(smaller * 0.2f, smaller); tmpVector2.set(radialDist, 0.0f); // rotates the specified vector angle rads around the origin // init and rotate the transformation matrix tmpMatrix3.idt().rotateRad(i * spacing); // now transform the object's vertices tmpVector2.mul(tmpMatrix3); wayPoints.add(new Vector3(tmpVector2.x, height, tmpVector2.y)); } return wayPoints; }
Example #4
Source File: HelpScreen.java From FruitCatcher with Apache License 2.0 | 6 votes |
@Override public boolean touchUp(int screenX, int screenY, int pointer, int button) { Vector3 touchPos = new Vector3(); touchPos.set(screenX, screenY, 0); camera.unproject(touchPos); for(int i=0;i<buttons.length;i++) { if (buttons[i].isPressed(touchPos)) { if (i == 0) { game.gotoMenuScreen(); } break; } } return true; }
Example #5
Source File: Terrain.java From Mundus with Apache License 2.0 | 6 votes |
/** * Get normal at world coordinates. The methods calculates exact point * position in terrain coordinates and returns normal at that point. If * point doesn't belong to terrain -- it returns default * <code>Vector.Y<code> normal. * * @param worldX * the x coord in world * @param worldZ * the z coord in world * @return normal at that point. If point doesn't belong to terrain -- it * returns default <code>Vector.Y<code> normal. */ public Vector3 getNormalAtWordCoordinate(float worldX, float worldZ) { transform.getTranslation(c00); float terrainX = worldX - c00.x; float terrainZ = worldZ - c00.z; float gridSquareSize = terrainWidth / ((float) vertexResolution - 1); int gridX = (int) Math.floor(terrainX / gridSquareSize); int gridZ = (int) Math.floor(terrainZ / gridSquareSize); if (gridX >= vertexResolution - 1 || gridZ >= vertexResolution - 1 || gridX < 0 || gridZ < 0) { return Vector3.Y.cpy(); } return getNormalAt(gridX, gridZ); }
Example #6
Source File: CarStillModel.java From uracer-kotd with Apache License 2.0 | 6 votes |
private Vector3 world2Dto3D (PerspectiveCamera camPersp, OrthographicCamera camOrtho, float posPxX, float posPxY) { float meshZ = -(camPersp.far - camPersp.position.z) + (camPersp.far * (1 - (camOrtho.zoom))); // compute position tmpvec.x = (this.positionOffsetPx.x - camPersp.position.x) + (camPersp.viewportWidth / 2) + posPxX; tmpvec.y = (this.positionOffsetPx.y + camPersp.position.y) + (camPersp.viewportHeight / 2) - posPxY; tmpvec.z = 1; tmpvec.x *= ScaleUtils.Scale; tmpvec.y *= ScaleUtils.Scale; tmpvec.x += ScaleUtils.CropX; tmpvec.y += ScaleUtils.CropY; // transform to world space camPersp.unproject(tmpvec, ScaleUtils.CropX, ScaleUtils.CropY, ScaleUtils.PlayWidth, ScaleUtils.PlayHeight); // build model matrix tmpvec.z = meshZ; return tmpvec; }
Example #7
Source File: ActuatorEntity.java From Entitas-Java with MIT License | 6 votes |
public ActuatorEntity replaceCameraActuator(Camera camera, short height, float damping, float minDistanceX, float minDistanceY, String followTagEntity) { CameraActuator component = (CameraActuator) recoverComponent(ActuatorComponentsLookup.CameraActuator); if (component == null) { component = new CameraActuator(camera, height, damping, minDistanceX, minDistanceY, followTagEntity); } else { component.actuator = (indexOwner) -> { Set<GameEntity> followEntities = Indexed .getTagEntities(followTagEntity); for (GameEntity followEntity : followEntities) { RigidBody rc = followEntity.getRigidBody(); Transform transform = rc.body.getTransform(); Vector3 position = camera.position; position.x += (transform.getPosition().x + minDistanceX - position.x) * damping; position.y += (transform.getPosition().y + minDistanceY - position.y) * height; } }; } replaceComponent(ActuatorComponentsLookup.CameraActuator, component); return this; }
Example #8
Source File: Ragdoll.java From GdxDemo3D with Apache License 2.0 | 6 votes |
/** * Updates the rigid body parts to follow nodes of the model instance */ private void updateBodiesToArmature() { // Ragdoll parts should follow the model animation. // Loop over each part and set it to the global transform of the armature node it should follow. capsuleTransform.set(modelTransform); for (Iterator<ObjectMap.Entry<btRigidBody, RigidBodyNodeConnection>> iterator = bodyPartMap.iterator(); iterator.hasNext(); ) { ObjectMap.Entry<btRigidBody, RigidBodyNodeConnection> entry = iterator.next(); RigidBodyNodeConnection data = entry.value; btRigidBody body = entry.key; Node followNode = data.followNode; Vector3 offset = data.bodyNodeOffsets.get(followNode); body.proceedToTransform(tmpMatrix.set(capsuleTransform) .mul(followNode.globalTransform).translate(offset)); } }
Example #9
Source File: CommandValue.java From Cubes with MIT License | 6 votes |
@Override public Float getArgument(String string, CommandSender sender) throws CommandParsingException { try { if (string.startsWith("@")) { Vector3 location = null; try { location = sender.getLocation(); } catch (UnsupportedOperationException ignored) {} if (location == null) throw new CommandParsingException("command.common.onlyPlayer"); if (string.length() == 1) return getComponent(location); return getComponent(location) + Float.parseFloat(string.substring(1)); } return Float.parseFloat(string); } catch (NumberFormatException e) { throw new CommandParsingException("command.common.value.coordinate.parsing"); } }
Example #10
Source File: SpawnBodiesSample.java From Codelabs with MIT License | 6 votes |
@Override public boolean touchUp(int screenX, int screenY, int pointer, int button) { /* Checks whether the max amount of balls were spawned */ if (spawnedBalls < MAX_SPAWNED_BALLS) { spawnedBalls++; /* Translate camera point to world point */ Vector3 unprojectedVector = new Vector3(); camera.unproject(unprojectedVector.set(screenX, screenY, 0)); /* Create a new ball */ Shape shape = Box2DFactory.createCircleShape(1); FixtureDef fixtureDef = Box2DFactory.createFixture(shape, 2.5f, 0.25f, 0.75f, false); Box2DFactory.createBody(world, BodyType.DynamicBody, fixtureDef, new Vector2(unprojectedVector.x, unprojectedVector.y)); } return true; }
Example #11
Source File: NavMeshGraph.java From GdxDemo3D with Apache License 2.0 | 6 votes |
/** * Creates a map over each triangle and its Edge connections to other triangles. Each edge must follow the * vertex winding order of the triangle associated with it. Since all triangles are assumed to have the same * winding order, this means if two triangles connect, each must have its own edge connection data, where the * edge follows the same winding order as the triangle which owns the edge data. * * @param indexConnections * @param triangles * @param vertexVectors * @return */ private static ArrayMap<Triangle, Array<Edge>> createSharedEdgesMap( Array<IndexConnection> indexConnections, Array<Triangle> triangles, Vector3[] vertexVectors) { ArrayMap<Triangle, Array<Edge>> connectionMap = new ArrayMap<Triangle, Array<Edge>>(); connectionMap.ordered = true; for (Triangle tri : triangles) { connectionMap.put(tri, new Array<Edge>()); } for (IndexConnection i : indexConnections) { Triangle fromNode = triangles.get(i.fromTriIndex); Triangle toNode = triangles.get(i.toTriIndex); Vector3 edgeVertexA = vertexVectors[i.edgeVertexIndex1]; Vector3 edgeVertexB = vertexVectors[i.edgeVertexIndex2]; Edge edge = new Edge(fromNode, toNode, edgeVertexA, edgeVertexB); connectionMap.get(fromNode).add(edge); fromNode.connections.add(edge); } return connectionMap; }
Example #12
Source File: BulletRaycastObstacleAvoidanceTest.java From gdx-ai with Apache License 2.0 | 6 votes |
@Override public void draw () { super.draw(); if (drawDebug) { Gdx.gl.glDisable(GL20.GL_DEPTH_TEST); Ray<Vector3>[] rays = rayConfigurations[rayConfigurationIndex].getRays(); shapeRenderer.begin(ShapeType.Line); shapeRenderer.setColor(1, 1, 0, 1); shapeRenderer.setProjectionMatrix(camera.combined); for (int i = 0; i < rays.length; i++) { Ray<Vector3> ray = rays[i]; shapeRenderer.line(ray.start, ray.end); } shapeRenderer.end(); Gdx.gl.glEnable(GL20.GL_DEPTH_TEST); } }
Example #13
Source File: ActuatorEntity.java From Entitas-Java with MIT License | 6 votes |
public ActuatorEntity addCameraActuator(Camera camera, short height, float damping, float minDistanceX, float minDistanceY, String followTagEntity) { CameraActuator component = (CameraActuator) recoverComponent(ActuatorComponentsLookup.CameraActuator); if (component == null) { component = new CameraActuator(camera, height, damping, minDistanceX, minDistanceY, followTagEntity); } else { component.actuator = (indexOwner) -> { Set<GameEntity> followEntities = Indexed .getTagEntities(followTagEntity); for (GameEntity followEntity : followEntities) { RigidBody rc = followEntity.getRigidBody(); Transform transform = rc.body.getTransform(); Vector3 position = camera.position; position.x += (transform.getPosition().x + minDistanceX - position.x) * damping; position.y += (transform.getPosition().y + minDistanceY - position.y) * height; } }; } addComponent(ActuatorComponentsLookup.CameraActuator, component); return this; }
Example #14
Source File: SimpleRoom.java From gdx-vr with Apache License 2.0 | 6 votes |
@Override public void render() { float deltaTime = Gdx.graphics.getDeltaTime(); if (Gdx.input.isKeyPressed(Input.Keys.W)) { VirtualReality.body.position.add(new Vector3(0, 0, -2).mul(VirtualReality.body.orientation).scl(deltaTime)); } if (Gdx.input.isKeyPressed(Input.Keys.S)) { VirtualReality.body.position.add(new Vector3(0, 0, 2).mul(VirtualReality.body.orientation).scl(deltaTime)); } if (Gdx.input.isKeyPressed(Input.Keys.A)) { VirtualReality.body.orientation.mulLeft(new Quaternion(Vector3.Y, 90f * deltaTime)); } if (Gdx.input.isKeyPressed(Input.Keys.D)) { VirtualReality.body.orientation.mulLeft(new Quaternion(Vector3.Y, -90f * deltaTime)); } VirtualReality.update(Gdx.graphics.getDeltaTime()); VirtualReality.renderer.render(); }
Example #15
Source File: Physics.java From gdx-proto with Apache License 2.0 | 5 votes |
/** finds the distance from the bottom of the passed dimensions to the ground. * This method uses the four corners of the dimensions * this is more expensive than checking a single point, but also more accurate * @return distance to the ground, or Float.NaN when raycast did not hit ground */ public float distanceFromGround(Vector3 position, Vector3 dimen) { lastDistanceFromGroundRayHitCount = 0; lastDistanceFromGroundAvgDist = 0f; float lowest = Float.NaN; float downStep = 2f + dimen.y; // length of ray // test four corners float x = dimen.x / 4f; float z = dimen.z / 4f; float rayOriginHeight = 0f; // by starting the ray from the center of the dimensions // we can catch cases where the dimensions are already partially // embedded underneath the ground. // in this case, a negative distance will be returned rectVectors[0].set(position).add(-x, rayOriginHeight, -z); rectVectors[1].set(position).add(-x, rayOriginHeight, z); rectVectors[2].set(position).add(x, rayOriginHeight, z); rectVectors[3].set(position).add(x, rayOriginHeight, -z); for (int i = 0; i < rectVectors.length; i++) { Vector3 point = rectVectors[i]; castRayStaticOnly(point, tmp.set(point).sub(0f, downStep, 0f)); if (raycastReport.hit) { lastDistanceFromGroundAvgDist += raycastReport.hitDistance; lastDistanceFromGroundRayHitCount++; if (Float.isNaN(lowest) || raycastReport.hitDistance < lowest) { lowest = raycastReport.hitDistance; } } } // we started the ray from the center, but we want the distance to ground from the bottom if (!Float.isNaN(lowest)) { // if embedded in ground, a negative value will be returned lowest -= (rayOriginHeight + dimen.y/2f); } lastDistanceFromGroundAvgDist /= lastDistanceFromGroundRayHitCount; return lowest; }
Example #16
Source File: LivingEntity.java From Radix with MIT License | 5 votes |
public int getBlockInFeet(IWorld world) { int x = MathUtils.floor(getPosition().getX()); int y = MathUtils.floor(getPosition().getY()); int z = MathUtils.floor(getPosition().getZ()); IChunk chunk = world.getChunk(x, z); if (chunk != null && y < world.getHeight()) { int cx = x & (world.getChunkSize() - 1); int cz = z & (world.getChunkSize() - 1); try { int id = chunk.getBlockId(cx, y, cz); Block block = RadixAPI.instance.getBlock(id); if (block == null) return 0; BoundingBox blockBox = block.calculateBoundingBox(chunk, cx, y, cz); float halfWidth = width / 2f; Vector3 bottomBackLeft = getPosition().cpy().add(-halfWidth, 0, -halfWidth); Vector3 bottomBackRight = bottomBackLeft.cpy().add(width, 0, 0); Vector3 bottomFrontRight = bottomBackRight.cpy().add(0, 0, width); Vector3 bottomFrontLeft = bottomBackLeft.cpy().add(width, 0, 0); boolean inFeet = blockBox.contains(bottomBackLeft) || blockBox.contains(bottomBackRight) || blockBox.contains(bottomFrontLeft) || blockBox.contains(bottomFrontRight); return inFeet ? id : 0; } catch (BlockStorage.CoordinatesOutOfBoundsException ex) { ex.printStackTrace(); return 0; } } else { return 0; } }
Example #17
Source File: HeightMapModel.java From gdx-proto with Apache License 2.0 | 5 votes |
public Vector3 getSurfaceNormalFromPos(Vector3 pos) { //HeightMapModel.Triangle tri = Main.heightMapModel.getTriangleAtWorldCoords(pos.x, pos.z); //System.out.println("got tri at: " + Tools.fmt(tri.getCenter(tmp))); //View.touchedTris.add(tri); TODO //tmp.set(tri.faceNormal); return tmp; }
Example #18
Source File: NavMeshDebugDrawer.java From GdxDemo3D with Apache License 2.0 | 5 votes |
private void drawPathPoints(NavMeshPointPath navMeshPointPath) { shapeRenderer.set(MyShapeRenderer.ShapeType.Line); Vector3 q; Vector3 p = navMeshPointPath.getVector(navMeshPointPath.getSize() - 1); shapeRenderer.setColor(Color.WHITE); for (int i = navMeshPointPath.getSize() - 1; i >= 0; i--) { q = navMeshPointPath.getVector(i); shapeRenderer.setColor(Color.CYAN); shapeRenderer.line(p, q); p = q; drawVertex(p, 0.02f, Color.WHITE); } }
Example #19
Source File: HeightMapModel.java From gdx-proto with Apache License 2.0 | 5 votes |
/** Return vertex normal based on average of surrounding triangle face normals */ private Vector3 calculateNormalForVertex(int z, int x) { tmp.set(0f, 0f, 0f); Triangle[] neighbors = getTrianglesNeighboringVertex(z, x); int triCount = 0; for (int i = 0; i < neighbors.length; i++) { Triangle tri = neighbors[i]; if (tri != null) { triCount++; tmp.add(tri.faceNormal); } } tmp.scl(1f / triCount); return tmp; }
Example #20
Source File: Shadow.java From gdx-proto with Apache License 2.0 | 5 votes |
public void update(Vector3 position) { // optimize for Mobile if (Main.isMobile() && Main.frame % 6 != 0) { // don't update height } else { height = Physics.inst.getShadowHeightAboveGround(position) - heightOffset; } tmp.set(position.x, position.y - height, position.z); modelInstance.transform.setToTranslation(tmp); modelInstance.transform.rotate(Vector3.Y, Physics.inst.raycastReport.hitNormal); }
Example #21
Source File: HelpScreen.java From ashley-superjumper with Apache License 2.0 | 5 votes |
public HelpScreen (SuperJumper game) { this.game = game; guiCam = new OrthographicCamera(); guiCam.setToOrtho(false, 320, 480); nextBounds = new Rectangle(320 - 64, 0, 64, 64); touchPoint = new Vector3(); helpImage = Assets.loadTexture("data/help1.png"); helpRegion = new TextureRegion(helpImage, 0, 0, 320, 480); }
Example #22
Source File: WorldGenerator.java From Skyland with MIT License | 5 votes |
private static void placeCave(Vector3 island) { Matrix4 transform = new Matrix4(); transform.setToTranslation(new Vector3(-5.4f, -.45f, -2.9f).add(island)); transform.rotate(new Vector3(0, 1, 0), -35); Builder.setBuildModel(Models.MODEL_CAVE_PROTOTYPE); Builder.build(transform); }
Example #23
Source File: ExplodeEffectFactory.java From Klooni1010 with GNU General Public License v3.0 | 5 votes |
@Override public void draw(Batch batch) { dead = true; // assume we're death final Vector3 translation = batch.getTransformMatrix().getTranslation(new Vector3()); for (int i = shards.length; i-- != 0; ) { shards[i].draw(batch, Gdx.graphics.getDeltaTime()); dead &= translation.y + shards[i].pos.y + shards[i].size < 0; // all must be dead } }
Example #24
Source File: Physics.java From gdx-proto with Apache License 2.0 | 5 votes |
private void executeRayCast(Vector3 position, Vector3 end, RayResultCallback callback) { raycastReport.reset(); world.rayTest(position, end, callback); raycastReport.hit = callback.hasHit(); if (raycastReport.hit) { float length = position.dst(end); raycastReport.hitDistance = length * callback.getClosestHitFraction(); if (callback instanceof ClosestRayResultCallback) { ClosestRayResultCallback cb = (ClosestRayResultCallback) callback; Vector3 normal = tmp; cb.getHitNormalWorld(tmp); raycastReport.hitNormal.set(normal.x, normal.y, normal.z); } } }
Example #25
Source File: Triangle.java From GdxDemo3D with Apache License 2.0 | 5 votes |
/** * Calculates a random point in this triangle. * * @param out Output vector * @return Output for chaining */ public Vector3 getRandomPoint(Vector3 out) { final float sr1 = (float) Math.sqrt(MathUtils.random()); final float r2 = MathUtils.random(); final float k1 = 1 - sr1; final float k2 = sr1 * (1 - r2); final float k3 = sr1 * r2; out.x = k1 * a.x + k2 * b.x + k3 * c.x; out.y = k1 * a.y + k2 * b.y + k3 * c.y; out.z = k1 * a.z + k2 * b.z + k3 * c.z; return out; }
Example #26
Source File: GameScene.java From Skyland with MIT License | 5 votes |
private void initWorld() { camera = WorldGenerator.generatePerspectiveCamera(1, 150, new Vector3(-8, 10, 15), new Vector3(0, 2, 0)); batch = new ModelBatch(); particleUtils = new ParticleUtils(); particleUtils.initBillBoardParticles(camera); //adding generators world = WorldGenerator.generateBaseWorld(false, false); cloudGenerator = new CloudGenerator(world, 30); environment = WorldGenerator.generateBaseEnvironment(new Vector3(-6, 14, 6)); WorldGenerator.createKinematicIsland(world, new Vector3(0, 0, 0), true); WorldHover.reinit(); }
Example #27
Source File: VectorUtil.java From Cubes with MIT License | 5 votes |
public static Float[] array(Vector3 vector3) { Float[] floats = new Float[3]; floats[0] = vector3.x; floats[1] = vector3.y; floats[2] = vector3.z; return floats; }
Example #28
Source File: MainMenuScreen.java From ashley-superjumper with Apache License 2.0 | 5 votes |
public MainMenuScreen (SuperJumper game) { this.game = game; guiCam = new OrthographicCamera(320, 480); guiCam.position.set(320 / 2, 480 / 2, 0); soundBounds = new Rectangle(0, 0, 64, 64); playBounds = new Rectangle(160 - 150, 200 + 18, 300, 36); highscoresBounds = new Rectangle(160 - 150, 200 - 18, 300, 36); helpBounds = new Rectangle(160 - 150, 200 - 18 - 36, 300, 36); touchPoint = new Vector3(); }
Example #29
Source File: GameCharacter.java From GdxDemo3D with Apache License 2.0 | 5 votes |
/** * Direction vector of an armature bone, in world coordinate system. * * @param nodeId Name of the bone * @param out Output vector * @return Output vector for chaining */ public Vector3 getBoneDirection(String nodeId, Vector3 out) { Node node = modelInstance.getNode(nodeId); Node endPointNode = (node.hasChildren()) ? node.getChild(0) : node; node.globalTransform.getTranslation(TMP_V1); endPointNode.globalTransform.getTranslation(TMP_V2); TMP_V1.sub(TMP_V2).scl(-1); modelInstance.transform.getRotation(TMP_Q); TMP_Q.transform(TMP_V1); return out.set(TMP_V1).nor(); }
Example #30
Source File: GdxPath.java From libGDX-Path-Editor with Apache License 2.0 | 5 votes |
public void setControlPath(ArrayList<Vector3> controlPath) { if (this.controlPath != null) { this.controlPath.clear(); this.controlPath = null; } if (controlPath == null) { return; } this.controlPath = new ArrayList<Vector3>(); Vector3 v; for (int i=0; i<controlPath.size(); i++) { v = controlPath.get(i); this.controlPath.add(new Vector3(v.x, v.y, 0f)); } }