I've researched this quite a bit but I can't seem to find why I'm getting this error. I've ruled out the origin of the error coming from anywhere but "Transform .java:38", so I don't think I need to include that code. Line 38 is followed by 4 asterisks(*).
Error:
Exception in thread "main" java.lang.NullPointerException
at com.base.engine.Transform.getProjectedTransformation(Transform.java:38)
at com.base.engine.Game.render(Game.java:67)
at com.base.engine.MainComponent.render(MainComponent.java:111)
at com.base.engine.MainComponent.run(MainComponent.java:102)
at com.base.engine.MainComponent.start(MainComponent.java:28)
at com.base.engine.MainComponent.main(MainComponent.java:126)
Code:
package com.base.engine;
public class Transform
{
private static Camera camera;
private static float zNear;
private static float zFar;
private static float width;
private static float height;
private static float fov;
private Vector3f translation;
private Vector3f rotation;
private Vector3f scale;
public Transform()
{
translation = new Vector3f(0,0,0);
rotation = new Vector3f(0,0,0);
scale = new Vector3f(1,1,1);
}
public Matrix4f getTransformation()
{
Matrix4f translationMatrix = new Matrix4f().initTranslation(translation.getX(), translation.getY(), translation.getZ());
Matrix4f rotationMatrix = new Matrix4f().initRotation(rotation.getX(), rotation.getY(), rotation.getZ());
Matrix4f scaleMatrix = new Matrix4f().initScale(scale.getX(), scale.getY(), scale.getZ());
return translationMatrix.mul(rotationMatrix.mul(scaleMatrix));
}
public Matrix4f getProjectedTransformation()
{
Matrix4f transformationMatrix = getTransformation();
Matrix4f projectionMatrix = new Matrix4f().initProjection(fov, width, height, zNear, zFar);
Matrix4f cameraRotation = new Matrix4f().initCamera(camera.getForward(), camera.getUp());
****Matrix4f cameraTranslation = new Matrix4f().initTranslation(-camera.getPos().getX(), -camera.getPos().getY(), -camera.getPos().getZ());
return projectionMatrix.mul(cameraRotation.mul(cameraTranslation.mul(transformationMatrix)));
}
public Vector3f getTranslation()
{
return translation;
}
public static void setProjection(float fov, float width, float height, float zNear, float zFar)
{
Transform.fov = fov;
Transform.width = width;
Transform.height = height;
Transform.zNear = zNear;
Transform.zFar = zFar;
}
public void setTranslation(Vector3f translation)
{
this.translation = translation;
}
public void setTranslation(float x, float y, float z)
{
this.translation = new Vector3f(x, y, z);
}
public Vector3f getRotation()
{
return rotation;
}
public void setRotation(Vector3f rotation)
{
this.rotation = rotation;
}
public void setRotation(float x, float y, float z)
{
this.rotation = new Vector3f(x, y, z);
}
public Vector3f getScale()
{
return scale;
}
public void setScale(Vector3f scale)
{
this.scale = scale;
}
public void setScale(float x, float y, float z)
{
this.scale = new Vector3f(x, y, z);
}
public static Camera getCamera()
{
return camera;
}
public static void setCamera(Camera camera)
{
Transform.camera = camera;
}
}
More Code:
package com.base.engine;
public class Camera
{
public static final Vector3f yAxis = new Vector3f(0,1,0);
private Vector3f pos;
private Vector3f forward;
private Vector3f up;
public Camera()
{
this(new Vector3f(0,0,0), new Vector3f(0,0,1), new Vector3f(0,1,0));
}
public Camera(Vector3f ps, Vector3f forward, Vector3f up)
{
this.pos = pos;
this.forward = forward;
this.up = up;
up.normalize();
forward.normalize();
}
public void move(Vector3f dir, float amt)
{
pos = pos.add(dir.mul(amt));
}
public void rotateY(float angle)
{
Vector3f Haxis = yAxis.cross(forward);
Haxis.normalize();
forward.rotate(angle, yAxis);
forward.normalize();
up = forward.cross(Haxis);
up.normalize();
}
public void rotateX(float angle)
{
Vector3f Haxis = yAxis.cross(forward);
Haxis.normalize();
forward.rotate(angle, Haxis);
forward.normalize();
up = forward.cross(Haxis);
up.normalize();
}
public Vector3f getLeft()
{
Vector3f left = up.cross(forward);
left.normalize();
return left;
}
public Vector3f getRight()
{
Vector3f right = forward.cross(up);
right.normalize();
return right;
}
public Vector3f getPos() {
return pos;
}
public void setPos(Vector3f pos) {
this.pos = pos;
}
public Vector3f getForward() {
return forward;
}
public void setForward(Vector3f forward) {
this.forward = forward;
}
public Vector3f getUp() {
return up;
}
public void setUp(Vector3f up) {
this.up = up;
}
}
here's the answer: you don't need to research anything. you get a NullPointerException when you dereference a null reference. run your code in a debugger and figure out why the reference in question is null when you don't think it should be null. you need to learn how to debug these things yourself.
There is a typo in the constructor:
Wrong:
public Camera(Vector3f ps, Vector3f forward, Vector3f up)
{
this.pos = pos;
this.forward = forward;
this.up = up;
up.normalize();
forward.normalize();
}
Correct:
public Camera(Vector3f pos, Vector3f forward, Vector3f up)
{
this.pos = pos;
this.forward = forward;
this.up = up;
up.normalize();
forward.normalize();
}
There should have been a warning about the variable ps.
Related
Right now, whenever my player turns, the camera turns with it. This was intentional, but I changed my mind on that feature when I inputted other camera controls, and right now, I can't seem to disable that functionality without breaking the whole camera system. I'm working with OpenGL and LWJGL, but I don't think knowledge in those will be too necessary for this. I basically want the camera not to turn as the player does. Thank you for your time, and have a
Here is the camera class:
package entities;
import org.lwjgl.input.Keyboard;
import org.lwjgl.util.vector.Vector3f;
public class Camera {
private float distanceFromPlayer = 50;
private float angleAroundPlayer = 0;
private Vector3f position = new Vector3f(10,20,10);
private float pitch = 45;
private float yaw;
private float roll;
private Player player;
public Camera(Player player){
this.player = player;
}
public void move(){
if(Keyboard.isKeyDown(Keyboard.KEY_LEFT)){
angleAroundPlayer -= 1;
}
if(Keyboard.isKeyDown(Keyboard.KEY_RIGHT)){
angleAroundPlayer += 1;
}
if(Keyboard.isKeyDown(Keyboard.KEY_UP)){
pitch += 1;
}
if(Keyboard.isKeyDown(Keyboard.KEY_DOWN)){
pitch -= 1;
}
float horizontalDistance = calculateHorizontalDistance();
float verticalDistance = calculateVerticalDistance();
calculateCameraPosition(horizontalDistance,verticalDistance);
this.yaw = 180 - (player.getRotY() + angleAroundPlayer);
}
public Vector3f getPosition() {
return position;
}
public float getPitch() {
return pitch;
}
public float getYaw() {
return yaw;
}
public float getRoll() {
return roll;
}
private float calculateHorizontalDistance(){
return (float)(distanceFromPlayer * Math.cos(Math.toRadians(pitch)));
}
private float calculateVerticalDistance(){
return (float)(distanceFromPlayer * Math.sin(Math.toRadians(pitch)));
}
private void calculateCameraPosition(float horizontalDistance, float verticalDistance){
float theta = player.getRotY() + angleAroundPlayer;
float offsetX = (float)(horizontalDistance * Math.sin(Math.toRadians(theta)));
float offsetZ = (float)(horizontalDistance * Math.cos(Math.toRadians(theta)));
position.x = player.getPosition().x - offsetX;
position.z = player.getPosition().z - offsetZ;
position.y = player.getPosition().y + verticalDistance;
}
}
And here is the player class:
package entities;
import models.TexturedModel;
import org.lwjgl.input.Keyboard;
import org.lwjgl.util.vector.Vector3f;
import renderEngine.DisplayManager;
public class Player extends Entity{
private static final float RUN_SPEED = 20;
private static final float TURN_SPEED = 180;
private static final float GRAVITY = -50;
private static final float JUMP_POWER = 40;
private static final float TERRAIN_HEIGHT = 0.5f;
private float currentSpeed = 0;
private float currentTurnSpeed = 0;
private float upwardsSpeed = 0;
private boolean isInAir = false;
public Player(TexturedModel model, Vector3f position, float rotX, float rotY, float rotZ, float scale) {
super(model, position, rotX, rotY, rotZ, scale);
}
public void move(){
checkInputs();super.increaseRotation(0,currentTurnSpeed * DisplayManager.getFrameTimeSeconds(),0);
float distance = currentSpeed * DisplayManager.getFrameTimeSeconds();
float dx = (float) (distance * Math.sin(Math.toRadians(super.getRotY())));
float dz = (float) (distance * Math.cos(Math.toRadians(super.getRotY())));
super.increasePosition(dx,0,dz);
upwardsSpeed += GRAVITY * DisplayManager.getFrameTimeSeconds();
super.increasePosition(0,upwardsSpeed * DisplayManager.getFrameTimeSeconds(),0);
if(super.getPosition().y < TERRAIN_HEIGHT){
upwardsSpeed =0;
isInAir = false;
super.getPosition().y = TERRAIN_HEIGHT;
}
}
private void jump(){
if(!isInAir){
this.upwardsSpeed = JUMP_POWER;
isInAir = true;
}
}
private void checkInputs(){
if(Keyboard.isKeyDown(Keyboard.KEY_W)){
this.currentSpeed = RUN_SPEED;
}
else if (Keyboard.isKeyDown(Keyboard.KEY_S)) {
this.currentSpeed = -RUN_SPEED;
}
else{
this.currentSpeed = 0;
}
if(Keyboard.isKeyDown(Keyboard.KEY_D)){
this.currentTurnSpeed = -TURN_SPEED;
}
else if(Keyboard.isKeyDown(Keyboard.KEY_A)){
this.currentTurnSpeed = TURN_SPEED;
}
else{
this.currentTurnSpeed = 0;
}
if(Keyboard.isKeyDown(Keyboard.KEY_SPACE)){
jump();
}
}
}
And if needed, here is the Entity Class:
package entities;
import models.TexturedModel;
import org.lwjgl.util.vector.Vector3f;
public class Entity {
private TexturedModel model;
private Vector3f position;
private float rotX,rotY,rotZ;
private float scale;
public Entity(TexturedModel model, Vector3f position, float rotX, float rotY, float rotZ,float scale){
this.model = model;
this.position = position;
this.rotX = rotX;
this.rotY = rotY;
this.rotZ = rotZ;
this.scale = scale;
}
public void increasePosition(float dx, float dy, float dz){
this.position.x += dx;
this.position.y += dy;
this.position.z += dz;
}
public void increaseRotation(float dx, float dy, float dz){
this.rotX += dx;
this.rotY += dy;
this.rotZ += dz;
}
public TexturedModel getModel() {
return model;
}
public Vector3f getPosition() {
return position;
}
public float getRotX() {
return rotX;
}
public float getRotY() {
return rotY;
}
public float getRotZ() {
return rotZ;
}
public float getScale() {
return scale;
}
public void setModel(TexturedModel model) {
this.model = model;
}
public void setPosition(Vector3f position) {
this.position = position;
}
public void setRotX(float rotX) {
this.rotX = rotX;
}
public void setRotY(float rotY) {
this.rotY = rotY;
}
public void setRotZ(float rotZ) {
this.rotZ = rotZ;
}
public void setScale(float scale) {
this.scale = scale;
}
}
I have a problem with moveTo() action. There is no error, but Actor is not moving to the position. The method is called in touchDown(). I spent a few hours and cant find the solution.
Please can you help? Parameters in moveTo() are random for now, so don't worry about it
Please see below the code.
public class GameScreen implements Screen, InputProcessor {
private final float REMOTE_WIDTH = 30;
private final float BATTERY_WIDTH = 11;
private final float BATTERY_HEIGHT = 30;
private final float TRIANGLE_X1 = RgbSortGame.GAME_SCREEN_WIDTH/2 - REMOTE_WIDTH /2;
private final float TRIANGLE_Y1 = RgbSortGame.GAME_SCREEN_HEIGHT/2;
private final float TRIANGLE_X2 = RgbSortGame.GAME_SCREEN_WIDTH/2 + REMOTE_WIDTH /2;
private final float TRIANGLE_Y2 = RgbSortGame.GAME_SCREEN_HEIGHT/2;
private final float TRIANGLE_X3 = RgbSortGame.GAME_SCREEN_WIDTH/2;
private final float TRIANGLE_Y3 = RgbSortGame.GAME_SCREEN_HEIGHT/2 - REMOTE_WIDTH;
private final float BUTTON_RADIUS = REMOTE_WIDTH/4f;
private final float TV_OFFSET_X = (RgbSortGame.GAME_SCREEN_WIDTH-RgbSortGame.GAME_SCREEN_WIDTH/2)/2;
private final float TV_OFFSET_Y = (RgbSortGame.GAME_SCREEN_HEIGHT-RgbSortGame.GAME_SCREEN_HEIGHT/4)/1.1f;
private Level level;
private List<BatteryView> batteryViews;
private Map<Integer, Battery> strategy;
private Viewport viewport;
private TextureAtlas atlas;
private OrthographicCamera camera;
private SpriteBatch batch;
private ShapeRenderer shapeRenderer;
private Texture background;
private Texture tv;
private Texture battery;
private Stage stage;
private Vector2 tempVector;
private Vector2 tempScreenToStage;
private Queue<String> hitActorsNames;
public GameScreen() {
Level1 level1 = new Level1();
level = new Level(level1.getRelativeCoordinates());
batteryViews = new ArrayList<>();
strategy = level.getBatteries();
batch = new SpriteBatch();
camera = new OrthographicCamera();
viewport = new StretchViewport(RgbSortGame.GAME_SCREEN_WIDTH, RgbSortGame.GAME_SCREEN_HEIGHT, camera);
viewport.apply();
stage = new Stage(viewport, batch);
Gdx.input.setInputProcessor(this);
shapeRenderer = new ShapeRenderer();
atlas = new TextureAtlas("buttons/buttons.atlas");
background = new Texture("images/97916b7c0f1f5f582723426ee1f876ce.jpg");
tv = new Texture("images/tv1.png");
battery = new Texture("images/battery.png");
camera.position.set(camera.viewportWidth / 2, camera.viewportHeight / 2, 0);
camera.update();
hitActorsNames = new ArrayDeque<>();
calculateBatteriesStartCoordinates();
tempVector = new Vector2(0,0);
tempScreenToStage = new Vector2(0,0);
}
#Override
public void show() {
}
#Override
public void render(float delta) {
batch.setProjectionMatrix(camera.combined);
batch.begin();
batch.draw(background, 0f,0f,RgbSortGame.GAME_SCREEN_WIDTH, RgbSortGame.GAME_SCREEN_HEIGHT);
batch.draw(tv, TV_OFFSET_X, TV_OFFSET_Y,
RgbSortGame.GAME_SCREEN_WIDTH/2, RgbSortGame.GAME_SCREEN_HEIGHT/4);
batch.end();
shapeRenderer.setProjectionMatrix(camera.combined);
shapeRenderer.begin(ShapeRenderer.ShapeType.Filled);
shapeRenderer.setColor(Color.GOLD);
shapeRenderer.triangle(TRIANGLE_X1, TRIANGLE_Y1,
TRIANGLE_X2, TRIANGLE_Y2,
TRIANGLE_X3, TRIANGLE_Y3);
shapeRenderer.end();
stage.draw();
stage.act(Gdx.graphics.getDeltaTime());
}
#Override
public void resize(int width, int height) {
viewport.update(width, height);
camera.position.set(camera.viewportWidth / 2, camera.viewportHeight / 2, 0);
camera.update();
}
#Override
public void pause() {
}
#Override
public void resume() {
}
#Override
public void hide() {
}
#Override
public void dispose() {
background.dispose();
batch.dispose();
shapeRenderer.dispose();
atlas.dispose();
stage.dispose();
}
public void calculateBatteriesStartCoordinates(){
float batteryStartPositionX = RgbSortGame.GAME_SCREEN_WIDTH/24;
for (int i = 0; i < strategy.size(); i++) {
if (batteryStartPositionX >= TRIANGLE_X1 && batteryStartPositionX<= TRIANGLE_X2){
batteryStartPositionX += REMOTE_WIDTH;
}
Actor batteryView = new BatteryView(batteryStartPositionX, TRIANGLE_Y3, BATTERY_WIDTH, BATTERY_HEIGHT, BUTTON_RADIUS, strategy.get(i), battery, atlas);
batteryStartPositionX += RgbSortGame.GAME_SCREEN_WIDTH/24 + BATTERY_WIDTH;
batteryView.setName(i + "");
stage.addActor(batteryView);
}
}
#Override
public boolean keyDown(int keycode) {
return false;
}
#Override
public boolean keyUp(int keycode) {
return false;
}
#Override
public boolean keyTyped(char character) {
return false;
}
#Override
public boolean touchDown(int screenX, int screenY, int pointer, int button) {
tempScreenToStage = stage.screenToStageCoordinates(tempVector.set((float)screenX,(float)screenY));
Actor hitActor = stage.hit(tempScreenToStage.x,tempScreenToStage.y,true);
if (hitActor != null){
hitActorsNames.add(hitActor.getName());
if (hitActorsNames.size() >= 2){
Actor actor = stage.getRoot().findActor(hitActorsNames.poll());
actor.addAction(Actions.moveTo(100f,200f,0.7f));
hitActorsNames.clear();
}
}
}
return true;
}
#Override
public boolean touchUp(int screenX, int screenY, int pointer, int button) {
return false;
}
#Override
public boolean touchDragged(int screenX, int screenY, int pointer) {
return false;
}
#Override
public boolean mouseMoved(int screenX, int screenY) {
return false;
}
#Override
public boolean scrolledenter code here(float amountX, float amountY) {
return false;
}
And BatteryView:
public class BatteryView extends Actor{
private float positionX;
private float positionY;
private float width;
private float height;
private float buttonRadius;
private Texture batteryTexture;
private Deque<GameButton> buttonsStrategy;
private TextureAtlas atlas;
public BatteryView(float positionX, float positionY, float width, float height,
float buttonRadius, Battery strategy,
Texture batteryTexture, TextureAtlas atlas) {
this.positionX = positionX;
this.positionY = positionY;
this.batteryTexture = batteryTexture;
this.width = width;
this.height = height;
this.atlas = atlas;
this.buttonRadius = buttonRadius;
this.buttonsStrategy = strategy.getGameButtons();
this.setBounds(positionX,positionY,width,height);
this.setTouchable(Touchable.enabled);
this.setSize(width, height);
}
#Override
public void act(float delta) {
super.act(delta);
}
#Override
public void draw(Batch batch, float parentAlpha){
batch.draw(batteryTexture,positionX,positionY,width,height);
float xButtonPosition = positionX + width / 2 - buttonRadius / 2;
float yButtonPosition = positionY;
for (GameButton gameButton : buttonsStrategy) {
new GameButtonView(xButtonPosition, yButtonPosition,
buttonRadius, atlas.findRegion(gameButton.getColor())).draw(batch);
yButtonPosition += buttonRadius;
}
}
public float getPositionX() {
return positionX;
}
public float getPositionY() {
return positionY;
}
public float getWidth() {
return width;
}`enter code here`
public float getHeight() {
return height;
}
}
Thank you in advance!
UPDATE: I found a solution! I had to change draw method in BatteryView class. It should be batch.draw(batteryTexture,getX(),getY(),width,height)instead off
batch.draw(batteryTexture,positionX,positionY,width,height).
How can I utilize my lerp function inside the vector3f class? Currently the lerp function reads like so:
public Vector3f lerp(Vector3f other, float alpha) {
return this.scale(1f - alpha).add(other.scale(alpha));
}
I have position and velocity vectors which use the add function as it updates. Now I want some smooth movement, but, I'm unsure how you would correctly use lerp. I've watched and read a few tutorials but none of them seem to address this kind of functionality. Any help would be much appreciated.
UPDATE:
So I've been watching this video here he has a series of videos on lerp with a very good diagram demonstration, which gave me a clue as to how linear interpolation works, so I decided to give it another shot. I wrote a new Vector2f method like so.
public Vector2f lerpT(Vector2f currentPos, Vector2f newPos, float alpha)
{
return currentPos.scale(1f - alpha).add(newPos.scale(alpha));
//return Vector3f point1 + alpha * (point2 - point1);
}
And my main class is like so:
public class Main {
public static void main(String[] args) throws IOException {
init();
}
public static void init() {
Vector2f currentPosition = new Vector2f(0.3f,0.7f);
Vector2f newPosition = new Vector2f(1.3f,0.8f);
Vector2f lerpPos = new Vector2f().lerpT(currentPosition, newPosition, 0f);
System.out.println("Testing LERP: " + "5/01/2018" + "\n");
System.out.println(lerpPos.x);
System.out.println(lerpPos.y);
}
This is what gets printed out into the console.
X: 0.79999995
Y: 0.75
I found some graph paper and decided to map it which was useful. I calculated the formula with a calculator and I get the same values in the x and y's lerpPos vector that is calculated in the code. I also changed it to Vector2f to make it simpler. And instead of LWJGL I decided to make a simple console program in java. While I understand it a bit more, I'm unsure how I'm supposed to use a velocity vector with the lerp function so I can give something some acceleration(?). I see how the alpha in the formula is important, but I'm unsure how to utilize it. If anything, I'd like to tryout some easing in and easing out, but the witchcraft needed seems a little bit over my head just at this moment. Oh well, I'll keep trying.
I'm going to post my completed code to my github, I'll post a link here when I get it up and running .Again, any help would be much appreciated
UPDATE:
public class Player {
private TexturedModel model;
public Vector3f position;
public Vector3f velocity;
public Vector3f acceleration;
public static Vector3f direction;
public static float maxVelocity = 0.5f;
private float rotX, rotY, rotZ;
private float scaleX, scaleY, scaleZ;
private float maxHolder;
public Player(TexturedModel model, Vector3f position, float rotX, float rotY, float rotZ,
float scaleX, float scaleY, float scaleZ) {
this.model = model;
this.rotX = rotX;
this.rotY = rotY;
this.rotZ = rotZ;
this.scaleX = scaleX;
this.scaleY = scaleY;
this.scaleZ = scaleZ;
this.position = position;
Random random = new Random();
position = new Vector3f();
velocity = new Vector3f();
acceleration = new Vector3f();
direction = new Vector3f();
}
public void update() {
velocity = velocity.add(acceleration);
position = position.add(velocity);
maxHolder = maxVelocity;
//position.length()
//Limit
if (velocity.length() > maxVelocity) {
velocity = velocity.normalize().scale(maxVelocity);
}
else if (velocity.dot(direction) < 0.0) {
velocity = new Vector3f(0,0,0);
}
}
public void movePlayer() {
if (KeyboardInput.isKeyDown(GLFW_KEY_D)) {
this.acceleration.x = 0.001f;
}
if (KeyboardInput.isKeyDown(GLFW_KEY_A)) {
this.acceleration.x = -0.001f;
}
if (KeyboardInput.isKeyDown(GLFW_KEY_W)) {
this.acceleration.y = 0.001f;
}
if (KeyboardInput.isKeyDown(GLFW_KEY_S)) {
this.acceleration.y = -0.001f;
}
if (!KeyboardInput.isKeyDown(GLFW_KEY_W) && !KeyboardInput.isKeyDown(GLFW_KEY_S) && !KeyboardInput.isKeyDown(GLFW_KEY_D) && !KeyboardInput.isKeyDown(GLFW_KEY_A)){
this.velocity.x = 0;
this.velocity.y = 0;
this.velocity.z = 0;
this.acceleration.x = 0f;
this.acceleration.y = 0;
this.acceleration.z = 0;
}
}
public void applyForce(Vector3f force) {
acceleration = force;
}
public void increasePosition(float dx, float dy, float dz) {
this.velocity.x += dx;
this.velocity.y += dy;
this.velocity.z += dz;
}
public void increaseRotation(float dx, float dy, float dz) {
this.rotX += dx;
this.rotY += dy;
this.rotZ += dz;
}
public TexturedModel getModel() {
return model;
}
public void setModel(TexturedModel model) {
this.model = model;
}
public void setVelocity(Vector3f velocity) {
this.velocity = velocity;
}
public Vector3f getPosition() {
return position;
}
public void setPosition(Vector3f position) {
this.position = position;
}
public float getRotX() {
return rotX;
}
public void setRotX(float rotX) {
this.rotX = rotX;
}
public float getRotY() {
return rotY;
}
public void setRotY(float rotY) {
this.rotY = rotY;
}
public float getRotZ() {
return rotZ;
}
public void setRotZ(float rotZ) {
this.rotZ = rotZ;
}
public float getScaleX() {
return scaleX;
}
public void setScaleX(float scaleX) {
this.scaleX = scaleX;
}
public float getScaleY() {
return scaleY;
}
public void setScaleY(float scaleY) {
this.scaleY = scaleY;
}
public float getScaleZ() {
return scaleZ;
}
public void setScaleZ(float scaleZ) {
this.scaleZ = scaleZ;
}
}
Heres the current code: It accelerates but velocity snaps back to 0 as I let go of the key. I want it to decelerate. Conceptually it should be easy.
I am render a square with in 3D space. When I use the glTranslatef() method and add a z coordinate the square is no longer visible. When the z coordinate is above 1 or below -1 then square is no longer displayed (I tested it by setting the z coordinate to 1. If and it didn't display).
Main.java
import java.util.logging.Level;
import java.util.logging.Logger;
import org.lwjgl.LWJGLException;
import org.lwjgl.opengl.Display;
import org.lwjgl.opengl.DisplayMode;
import static org.lwjgl.opengl.GL11.*;
public class Main {
/**
* #param args
*/
public static void main(String[] args) {
initDisplay();
gameLoop();
cleanUp();
}
public static void initDisplay(){
try {
Display.setDisplayMode(new DisplayMode(800, 600));
Display.setTitle("AWESOMENESS!");
Display.create();
} catch (LWJGLException e) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, e);
}
}
public static void gameLoop(){
Camera cam = new Camera(70, (float)Display.getWidth() / (float)Display.getHeight(), 0.3f, 1000);
while(!Display.isCloseRequested()){
glClear(GL_COLOR_BUFFER_BIT);
glLoadIdentity();
cam.useView();
glPushMatrix();{
glColor3f(1.0f, 0.5f, 0f);
//This is the problematic line. When the 3rd param goes above 1 or below -1 the
//square disappers.
glTranslatef(0,0,-10);
glBegin(GL_QUADS);{
glVertex3f(0,0,0);
glVertex3f(0,1,0);
glVertex3f(1,1,0);
glVertex3f(1,0,0);
}
glEnd();
}
glPopMatrix();
Display.update();
}
}
public static void cleanUp(){
Display.destroy();
}
}
Camera.java
import static org.lwjgl.opengl.GL11.*;
import static org.lwjgl.util.glu.GLU.*;
public class Camera {
//Position
private float x;
private float y;
private float z;
//Rotation
private float rx;
private float ry;
private float rz;
private float fov;
private float aspect;
private float near;
private float far;
public Camera(float fov, float aspect, float near, float far) {
x = 0;
y = 0;
z = 0;
rx = 0;
ry = 0;
rz = 0;
this.fov = fov;
this.aspect = aspect;
this.near = near;
this.far = far;
initProjection();
}
private void initProjection(){
glMatrixMode(GL_PROJECTION_MATRIX);
glLoadIdentity();
gluPerspective(fov, aspect, near, far);
glMatrixMode(GL_MODELVIEW);
}
public void useView(){
glRotatef(rx, 1, 0, 0);
glRotatef(ry, 0, 1, 0);
glRotatef(rz, 0, 0, 1);
glTranslatef(x, y, z);
}
public float getX() {
return x;
}
public float getY() {
return y;
}
public float getZ() {
return z;
}
public float getRx() {
return rx;
}
public float getRy() {
return ry;
}
public float getRz() {
return rz;
}
public float getFov() {
return fov;
}
public float getAspect() {
return aspect;
}
public float getNear() {
return near;
}
public float getFar() {
return far;
}
public void setX(float x) {
this.x = x;
}
public void setY(float y) {
this.y = y;
}
public void setZ(float z) {
this.z = z;
}
public void setRx(float rx) {
this.rx = rx;
}
public void setRy(float ry) {
this.ry = ry;
}
public void setRz(float rz) {
this.rz = rz;
}
public void setFov(float fov) {
this.fov = fov;
}
public void setAspect(float aspect) {
this.aspect = aspect;
}
public void setNear(float near) {
this.near = near;
}
public void setFar(float far) {
this.far = far;
}
}
glMatrixMode(GL_PROJECTION_MATRIX);
Instead should be:
glMatrixMode(GL_PROJECTION);
GL_PROJECTION_MATRIX does not render the 3rd dimension. There is no further documentation on this matter.
I have array list of circles, whitch are drawing by canvas. And everything is OK. But I need change all X,Y coordinates of circles, by during the program.
static ArrayList<Circle> mCircles;
private static void createCircles() {
if (mCircles == null) {
mCircles = new ArrayList<Circle>();
}
int rana = 66/(koeficient);
mCircles.add(new Circle(80, 200, rana));
}
public static void AddCircle() {
int rana = 66/(koeficient);
mCircles.add(new Circle(80, 200, rana));
}
private void Drawing(Canvas canvas) {
for (Circle c : mCircles) {
canvas.drawCircle(c.getCurrentX(), c.getCurrentY(), c.getRadius(),
mMalovani);
}
}
public static Circle findCircleClosestToTouchEvent(float x, float y) {
Circle c = mCircles.get(mCircles.size() - 1);
return c;
}
public class Circle extends Shape {
final float mRadius;
public Circle(float x, float y, float r) {
super(x, y);
mRadius = r;
}
final float getRadius() {
return mRadius;
}
}
public class Shape extends Activity {
protected float mStartX = 0f;
protected float mStartY = 0f;
public float mCurrentX = 30f;
public float mCurrentY = 30f;
protected float mActionDownX;
protected float mActionDownY;
protected float mActionMoveOffsetX;
protected float mActionMoveOffsetY;
// x y coordinate of a move action
public Shape (float x, float y) {
mStartX = x;
mStartY = y;
mCurrentX = x;
mCurrentY = y;
}
public void setStartX(float x) { mStartX = x; }
public void setStartY(float y) { mStartY = y; }
public float getCurrentX() { return mCurrentX; }
public float getCurrentY() { return mCurrentY; }
public void setCurrentX(float x) { mCurrentX = x;
}
public void setCurrentY(float y) { mCurrentY = y; }
public void setActionMoveOffsetX(float x) { mActionMoveOffsetX = x; }
public void setActionMoveOffsetY(float y) { mActionMoveOffsetY = y; }
public float getActionMoveOffsetX() { return mActionMoveOffsetX; }
public float getActionMoveOffsetY() { return mActionMoveOffsetY; }
public void setActionDownX(float x) { mActionDownX = x; }
public void setActionDownY(float y) { mActionDownY = y; }
public float getActionDownX() { return mActionDownX; }
public float getActionDownY() { return mActionDownY; }
public void restoreStartPosition() {
mCurrentX = mStartX;
mCurrentY = mStartY;
}
}
Assuming you have setCurrentX and setCurrentY methods opposite the getter methods, just loop through the list of circles.
private void changeCoordinates(List<Circle> circles, int x, int y){
for(Circle c:circles){
c.setCurrentX(x);
c.setCurrentY(y);
}
}