I'm trying to develop a small tower defense game with libGDX and am getting the following exception:
Exception in thread "LWJGL Application" java.lang.NullPointerException
at com.badlogic.gdx.graphics.g2d.SpriteBatch.switchTexture(SpriteBatch.java:1067)
at com.badlogic.gdx.graphics.g2d.SpriteBatch.draw(SpriteBatch.java:558)
at com.badlogic.gdx.graphics.g2d.Sprite.draw(Sprite.java:517)
at levels.AISprite.draw(AISprite.java:33)
at levels.levelGenerator.render(levelGenerator.java:44)
at com.badlogic.gdx.backends.lwjgl.LwjglApplication.mainLoop(LwjglApplication.java:232)
at com.badlogic.gdx.backends.lwjgl.LwjglApplication$1.run(LwjglApplication.java:127)
I understand that there is something that is not initialized, but what? Would be really happy if you could help me and explain whats the issue.
I would also be glad if you could improve my code! Thanks in advance
Code (only where the magic happens):
levelGenerator Class
public class levelGenerator extends ApplicationAdapter {
private final String level;
SpriteBatch batch;
Texture img;
Scorpion scorpion;
private Array<AISprite> aiSprites;
public levelGenerator(String level){
this.level = level;
}
#Override
public void create () {
Gdx.graphics.setTitle("Tower Defense Game");
scorpion = new Scorpion();
img = new Texture(level);
scorpion.createImage();
aiSprites = new Array<AISprite>();
aiSprites.add(new AISprite(scorpion, LevelOne.levelOnePath()));
}
public void render () {
batch = new SpriteBatch();
batch.begin();
//just the level image background
batch.draw(img, 0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
scorpion.renderImage();
for(AISprite aiSprite: aiSprites){
aiSprite.draw(batch);
}
for(AISprite aiSprite: aiSprites){
Vector2 previous = aiSprite.getPath().first();
for(Vector2 waypoint: aiSprite.getPath()){
previous = waypoint;
}
}
}
#Override
public void dispose () {
batch.dispose();
img.dispose();
scorpion.disposeImage();
}
}
Entity Class:
public class Entity extends Sprite {
String atlasPath;
private Animation<TextureRegion> animation;
private TextureAtlas entityAtlas;
private float timePassed = 0;
SpriteBatch batch;
public Entity(String atlasPath){
this.atlasPath = atlasPath;
}
public void createImage(){
// path for scorpion atlas file: "assetsPack/scorpions/scorpionRunning/scorpionPack.atlas"
entityAtlas = new TextureAtlas(Gdx.files.internal(atlasPath));
animation = new Animation<TextureRegion>(1/40f, entityAtlas.getRegions());
}
public void renderImage(){
batch = new SpriteBatch();
batch.begin();
timePassed += Gdx.graphics.getDeltaTime();
batch.draw(animation.getKeyFrame(timePassed, true), 0, 0);
batch.end();
}
public void disposeImage(){
entityAtlas.dispose();
}
}
Scorpion (Entity) Class:
public class Scorpion extends Entity {
public Scorpion(){
super("assetsPack/scorpions/scorpionRunning/scorpionPack.atlas");
}
Next class is the one for the pathfinding of the entities
public class AISprite extends Sprite {
private Vector2 velocity = new Vector2();
private float speed = 100, tolerance = 3;
public Array<Vector2> getPath() {
return path;
}
private Array<Vector2> path;
private int waypoint = 0;
public AISprite(Entity entity, Array<Vector2> path){
super(entity);
this.path = path;
}
public void draw(SpriteBatch spriteBatch){
update(Gdx.graphics.getDeltaTime());
super.draw(spriteBatch);
}
public void update(float delta){
float angle = (float) Math.atan2(path.get(waypoint).y - getY(), path.get(waypoint).x - getX());
velocity.set((float) Math.cos(angle) * speed, (float) Math.sin(angle) * speed);
setPosition(getX() + velocity.x * delta, getY() + velocity.y * delta);
if(isWaypointReached()){
setPosition(path.get(waypoint).x, path.get(waypoint).y);
if(waypoint + 1 >= path.size){
waypoint = 0;
}
else{
waypoint++;
}
}
}
public boolean isWaypointReached(){
return path.get(waypoint).x - getX() <= speed / tolerance * Gdx.graphics.getDeltaTime() && path.get(waypoint).y - getY() <= speed / tolerance * Gdx.graphics.getDeltaTime() ;
}
}
use a debugger, set a breakpoint on levels.levelGenerator.render(levelGenerator.java:44), and check what causes the erro .... if you never used a debugger, I strongly(!!!) recommend you learn how to use one before you continue with libgdx
Make sure that all your Gdx calls are made after the create() method is called. All gdx objects are null before that point, so calls such as Gdx.graphics.(...) or Gdx.app.(...) or Gdx.audio.(...) etc. will throw a NPE
Related
I have global variables called:
private int currentLevel;
private int mapHeight;
I have a constructor for my game, where currentLevel = level entered when setScreen() method is called:
public ElevatorLevel(Game g, int level)
{
super(g, level);
currentLevel = level;
}
In my create() method, I set mapHeight to 750 * currentLevel (which starts as one), however when I try to spawn in the blades as seen below, they spawn between -200 and 300. This is because the program is not recognizing currentLevel (I am assuming), so it is multiplying it by nothing, resulting with -200.
public void create()
{
world = new World(new Vector2(0, -9.8f), true);
timeElapsed = 0;
mapHeight = 750 * currentLevel;
blade = new PhysicsActor();
blade.storeAnimation( "", exTex );
blade.setOriginCenter();
blade.circularBoundary();
blade.setMaxSpeed(50);
blade.setDeceleration(50);
bladesList = new ArrayList<PhysicsActor>();
for (int i = 0; i < 3 ; i++)
{
blades = blade.clone();
float xCoord = randomFloatGenerator(440, 20);
float yCoord = randomFloatGenerator(mapHeight - 200, 300);
blades.setPosition(xCoord, yCoord);
mainStage.addActor(blades);
bladesList.add(blades);
}
I also have a Label in my update(float dt) method that is set to:
timeLabel.setText("Level: " + currentLevel);
As seen in the image above, currentLevel is recognized by the label, but not by mapHeight in create().
How do I get currentLevel to be recognized by the create() method?
Below is the standart portrait app code that i use almost in every libgdx project. I never use create method. Instead I use constructor, this code is the most bugfree one that i could have found.
GAME OR MENU SCREEN:
public class TutorialScreen implements Screen {
private OrthographicCamera camera;
public static final float WORLD_HEIGHT = 240;
public static final float WORLD_WIDTH = 135;
private Viewport viewport;
private Stage stage;
private EntryPoint game;
private AdsController adsController;
public TutorialScreen(final EntryPoint game, final AdsController adsController){
this.adsController = adsController;
this.game = game;
adsController.hideBannerAd();
float aspectRatio = (float) (Gdx.graphics.getHeight() / Gdx.graphics.getWidth());
camera = new OrthographicCamera(aspectRatio * WORLD_WIDTH, WORLD_HEIGHT);
camera.setToOrtho(false);
viewport = new FitViewport(WORLD_WIDTH , WORLD_HEIGHT,camera );
stage = new Stage(viewport, game.batch);
}
#Override
public void show() {
}
#Override
public void render(float delta) {
stage.draw();
stage.act();
}
#Override
public void resize(int width, int height) {
}
#Override
public void pause() {
}
#Override
public void resume() {
}
#Override
public void hide() {
}
#Override
public void dispose() {
}
}
ENTRY POINT THAT YOUR APP WILL OPEN FIRST:
package some.package;
public class EntryPoint extends Game {
SpriteBatch batch;
final AdsController adsController;
public EntryPoint(final AdsController adsController ){
this.adsController = adsController; //Interface for admob
}
#Override
public void create () {
batch = new SpriteBatch();
this.setScreen(new YourScreenClass(this,adsController)); //Above is tutorial so this would be new TutorialScreen(this,adsController)
}
#Override
public void render () {
Gdx.gl.glClearColor(0, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
batch.begin();
batch.end();
super.render();
}
#Override
public void dispose () {
batch.dispose();
}
}
Might have missed some curly brackets or ";" but you get the idea. This way you would not encounter any reference issues.
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
For some reason, when I try to pass through Gdx.graphics.getDeltaTime() into my player class, the float delta time is null giving a null pointer exception. I already tried to check if the getDeltaTime method worked, and its counting, but when i try to pass through the function it doesn't work.
My Main Code
public class MyGdxGame extends ApplicationAdapter implements InputProcessor {
SpriteBatch batch;
private Player1 player1;
private TiledMap iceLevel;
private OrthogonalTiledMapRenderer renderer;
private OrthographicCamera camera;
float elaspedTime;
#Override
public void create() {
batch = new SpriteBatch();
Gdx.input.setInputProcessor(this);
TmxMapLoader loader = new TmxMapLoader();
iceLevel = loader.load("IceLevel.tmx");
renderer = new OrthogonalTiledMapRenderer(iceLevel);
camera = new OrthographicCamera();
camera.setToOrtho(false);
player1 = new Player1(new Sprite(new Texture("player1Right.png")), (TiledMapTileLayer) iceLevel.getLayers().get("Land"));
player1.setPosition(player1.getCollisionLayer().getTileWidth(), 6 * player1.getCollisionLayer().getTileHeight());
}
#Override
public void render() {
player1.update(Gdx.graphics.getDeltaTime());
Gdx.gl.glClearColor(1, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
batch.begin();
camera.update();
renderer.setView(camera);
renderer.render();
renderer.getBatch().begin();
player1.draw(renderer.getBatch());
renderer.getBatch().end();
batch.end();
}
#Override
public void dispose() {
batch.dispose();
iceLevel.dispose();
renderer.dispose();
player1.getTexture().dispose();
}
A part of my player class
public class Player1 extends Sprite implements InputProcessor {
private Vector2 velocity;
private float speed = 60 * 2;
private float gravity = 60 * 1.8f;
private TiledMapTileLayer collisionLayer;
public Player1(Sprite sprite, TiledMapTileLayer collisionLayer) {
super(sprite);
this.collisionLayer = collisionLayer;
}
public void draw(SpriteBatch spriteBatch) {
update(Gdx.graphics.getDeltaTime());
super.draw(spriteBatch);
}
public void update(float delta) {
//gravity
velocity.y -= gravity * delta;
//set limit
if (velocity.y > speed) {
velocity.y = speed;
} else if (velocity.y < -speed) {
velocity.y = -speed;
}
// save old position
float oldX = getX();
float oldY = getY();
boolean collisionX = false;
boolean collisionY = false;
// move on x
setX(getX() + velocity.x * delta);
if (velocity.x < 0) { //going left
collisionX = collidesLeft();
} else if (velocity.x > 0) { //going right
collisionX = collidesRight();
}
// react to x collision
if (collisionX) {
setX(oldX);
velocity.x = 0;
}
// move on y
setY(getY() + velocity.y * delta * 5f);
if (velocity.y < 0) { // going down
collisionY = collidesBottom();
} else if (velocity.y > 0) { // going up
collisionY = collidesTop();
}
if (collisionY) {
setY(oldY);
velocity.y = 0;
}
}
Just to rule out delta time refactor you code like this:-
#Override
public void render() {
float delta = Gdx.graphics.getDeltaTime();
// Log or print this
if(delta > 0){
player1.update(Gdx.graphics.getDeltaTime());
Gdx.gl.glClearColor(1, 0, 0, 1);
.......
.......
}
Sounds like your player class update() method is the issue, but not the float delta. Looks like it is velocity. It is null.
private Vector2 velocity;
...
//gravity
velocity.y -= gravity * delta;
You are trying to set the y public float value of velocity (Vector2) but you don't have a velocity object instantiated.
Try
private Vector2 velocity = new Vector2();
I have a animation which i want to flip to the left if key LEFT is pressed, but it doesnt stay flipped. It only flips like 1 frame then turns back again.
Here is my GameScreen where i draw everything:
public class GameScreen extends ScreenManager{
//For the view of the game and the rendering
private SpriteBatch batch;
private OrthographicCamera cam;
//DEBUG
private Box2DDebugRenderer b2dr;
//World, Player and so on
private GameWorld world;
private Player player;
private Ground ground;
//player animations
private TextureRegion currFrame;
public static float w, h;
public GameScreen(Game game) {
super(game);
//vars
w = Gdx.graphics.getWidth();
h = Gdx.graphics.getHeight();
//view and rendering
batch = new SpriteBatch();
cam = new OrthographicCamera();
cam.setToOrtho(false, w/2, h/2);
//debug
b2dr = new Box2DDebugRenderer();
//world, bodies ...
world = new GameWorld();
player = new Player(world);
ground = new Ground(world);
}
#Override
public void pause() {
}
#Override
public void show() {
}
#Override
public void render(float delta) {
//clearing the screen
Gdx.gl.glClearColor(0, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
//updating
update(Gdx.graphics.getDeltaTime());
player.stateTime += Gdx.graphics.getDeltaTime();
//render
batch.setProjectionMatrix(cam.combined);
currFrame = Player.anim.getKeyFrame(Player.stateTime, true);
batch.begin();
batch.draw(currFrame, Player.body.getPosition().x * PPM - 64, Player.getBody().getPosition().y * PPM- 72);
batch.end();
//debug
b2dr.render(GameWorld.getWorld(), cam.combined.scl(PPM));
}
#Override
public void resize(int width, int height) {
}
#Override
public void hide() {
}
#Override
public void dispose() {
}
#Override
public void onKlick(float delta) {
}
public void update(float delta){
world.update(delta);
updateCam(delta);
Player.keyInput(delta);
System.out.println("X-POS" + Player.getBody().getPosition().x);
System.out.println("Y-POS" + Player.getBody().getPosition().y);
}
public void updateCam(float delta){
Vector3 pos = cam.position;
pos.x = Player.getBody().getPosition().x * PPM;
pos.y = Player.getBody().getPosition().y * PPM;
cam.position.set(pos);
cam.update();
}
}
and this is the Player class where the animation is:
public class Player {
public static Body body;
public static BodyDef def;
private FixtureDef fd;
//textures
public static Texture texture;
public static Sprite sprite;
public static TextureRegion[][] region;
public static TextureRegion[] idle;
public static Animation<TextureRegion> anim;
public static float stateTime;
//set form
private PolygonShape shape;
private GameScreen gs;
public Player(GameWorld world){
texture = new Texture(Gdx.files.internal("player/char_animation_standing.png"));
region = TextureRegion.split(texture, texture.getWidth() / 3, texture.getHeight() / 2);
idle = new TextureRegion[6];
int index = 0;
for(int i = 0; i < 2; i++){
for(int j = 0; j < 3; j++){
sprite = new Sprite(region[i][j]);
idle[index++] = sprite;
}
}
anim = new Animation<TextureRegion>(1 / 8f, idle);
stateTime = 0f;
def = new BodyDef();
def.fixedRotation = true;
def.position.set(gs.w / 4, gs.h / 4);
def.type = BodyType.DynamicBody;
body = world.getWorld().createBody(def);
shape = new PolygonShape();
shape.setAsBox(32 / 2 / PPM, 64/ 2 / PPM);
fd = new FixtureDef();
fd.shape = shape;
fd.density = 30;
body.createFixture(fd);
shape.dispose();
}
public static Body getBody() {
return body;
}
public static BodyDef getDef() {
return def;
}
public static Texture getTexture() {
return texture;
}
public static void keyInput(float delta){
int horizonForce = 0;
if(Gdx.input.isKeyJustPressed(Input.Keys.UP)){
body.applyLinearImpulse(0, 300f, body.getWorldCenter().x, body.getWorldCenter().y, true);
//body.applyForceToCenter(0, 1200f, true);
System.out.println("PRESSED");
}
if(Gdx.input.isKeyPressed(Input.Keys.LEFT)){
horizonForce -= 1;
sprite.flip(!sprite.isFlipX(), sprite.isFlipY());
}
if(Gdx.input.isKeyPressed(Input.Keys.RIGHT)){
horizonForce += 1;
}
body.setLinearVelocity(horizonForce * 20, body.getLinearVelocity().y);
}
}
thank you in advance and any answer is appreciated :D
Your sprite variable contain only one frame at the time of pressing left key. So, it flip that current sprite of your animation frame.
To solve the Problem you have to flip all the animation frame on pressing the left key.
You're only flipping last frame of Animation by sprite reference, You need to flip all frames of your Animation anim. You can flip in this way :
if(keycode== Input.Keys.RIGHT) {
for (TextureRegion textureRegion:anim.getKeyFrames())
if(!textureRegion.isFlipX()) textureRegion.flip(true,false);
}
else if(keycode==Input.Keys.LEFT) {
for (TextureRegion textureRegion:anim.getKeyFrames())
if(textureRegion.isFlipX()) textureRegion.flip(true,false);
}
I have made a class for the level generation and have got so far with it:
public class LevelGenerator {
private Sprite environment;
private float leftEdge, rightEdge, minGap, maxGap, y;
public Enemy enemy;
public LevelGenerator(Sprite environment, float leftEdge, float rightEdge,
float minGap, float maxGap) {
this.environment = environment;
this.leftEdge = leftEdge;
this.rightEdge = rightEdge;
this.minGap = minGap;
this.maxGap = maxGap;
}
public void generate(float topEdge){
if(y + MathUtils.random(minGap, maxGap) < topEdge)
return;
y = topEdge;
float x = MathUtils.random(leftEdge, rightEdge);
}
Basically, what I want to happen is for the enemy block to randomly generate on the sides of the screen. Here is the enemy block class (very simple):
public class Enemy extends Sprite{
public Enemy(Sprite sprite) {
super(sprite);
}
#Override
public void draw(Batch spriteBatch){
super.draw(spriteBatch);
}
}
This is what the game looks like at the moment when the block is just simply drawn on the game screen in a static position: http://i.imgur.com/SIt18Qn.png. What I am trying to achieve is for these "enemy" blocks to spawn randomly on either side of the screen but I can't seem to figure out a way to do it with the code I have so far.
Thank you!
I could not test but I think it will be fine, you have a rectangle if you want to see if it collides with another actor, if so updates its position in the update and draw method, and ramdon method start customizing to see if the coordinates, which colicionan be assigned to another actor rectagulo enemy or bye.
public class overFlowEnemy extends Sprite {
private final float maxH = Gdx.graphics.getHeight();
private final float maxW = Gdx.graphics.getWidth();
private Rectangle rectangle;
private Random random = new Random();
private float inttt = 0;
private float randomN = 0;
private boolean hasCollided = false;
public overFlowEnemy(Sprite sprite) {
super(sprite);
crearEnemigo();
rectangle = new Rectangle(getX(), getY(), getWidth(), getHeight());
}
#Override
public void draw(Batch spriteBatch) {
super.draw(spriteBatch);
}
private void crearEnemigo(){
setX(RandomNumber((int)maxW));
setY(RandomNumber((int)maxH));
}
private int RandomNumber(int pos) {
random.setSeed(System.nanoTime() * (long) inttt);
this.randomN = random.nextInt(pos);
inttt += randomN;
return (int)randomN;
}
public Rectangle getColliderActor(){
return this.rectangle;
}
}
the class as this should create a random enemy.
Edit: rereading your question, is that my English is not very good, and I think you wanted to be drawn only on the sides of the screen if so, tell me or adapts the class because when you create thought, which was across the screen.
I just added another class, if you can and want to work as you tell me which is correct, and delete the other.
public class overFlow extends Sprite {
private final float maxH = Gdx.graphics.getHeight();
private final float maxW = Gdx.graphics.getWidth();
private Rectangle rectangle;
private Random random = new Random();
private float inttt = 0;
private float randomN = 0;
private boolean hasCollided = false;
public overFlow(Sprite sprite) {
super(sprite);
crearEnemigo();
rectangle = new Rectangle(getX(), getY(), getWidth(), getHeight());
}
#Override
public void draw(Batch spriteBatch) {
super.draw(spriteBatch);
}
private void crearEnemigo(){
setX(RandomNumber((int)maxW, true));
setY(RandomNumber((int)maxH, false));
}
private int RandomNumber(int pos, boolean w) {
random.setSeed(System.nanoTime() * (long) inttt);
if (w = true){
this.randomN = random.nextInt((pos));
if(randomN % 2 == 0){
randomN = (pos - getWidth());
}else{
randomN = 0; //left screen
}
}else{
this.randomN = random.nextInt(pos - (int)getHeight());
}
inttt += randomN;
return (int)randomN;
}
public Rectangle getColliderActor(){
return this.rectangle;
}
}
I am trying to make a game engine and I want a camera controlled by the player and also effected by other jBullet entities in Java. I got suggested to use Kinematic Objects so I looked up about them. I couldn't find any documentation which I could understand.
Can someone explain how to set up and use kinematic objects or at least show me where I can start?
The documentation for KinematicCharacterController, found here isn't too entirely helpful, but the source in the CharacterDemo can be. Two main properties are defined in the demo.
public KinematicCharacterController character;
public PairCachingGhostObject ghostObject;
The ghost can be used for dynamic collision detection, as it does not automatically react to those events. The character can be moved by changing the Transform.
//from the source src\com\bulletphysics\demos\character\CharacterDemo.java
Transform startTransform = new Transform();
startTransform.setIdentity();
startTransform.origin.set(0.0f, 4.0f, 0.0f);
Vector3f worldMin = new Vector3f(-1000f,-1000f,-1000f);
Vector3f worldMax = new Vector3f(1000f,1000f,1000f);
AxisSweep3 sweepBP = new AxisSweep3(worldMin, worldMax);
ghostObject = new PairCachingGhostObject();
ghostObject.setWorldTransform(startTransform);
sweepBP.getOverlappingPairCache().setInternalGhostPairCallback(new GhostPairCallback());
float characterHeight = 1.75f * characterScale;
float characterWidth = 1.75f * characterScale;
ConvexShape capsule = new CapsuleShape(characterWidth, characterHeight);
ghostObject.setCollisionShape(capsule);
ghostObject.setCollisionFlags(CollisionFlags.CHARACTER_OBJECT);
float stepHeight = 0.35f * characterScale;
character = new KinematicCharacterController(ghostObject, capsule, stepHeight);
dynamicsWorld.addCollisionObject(ghostObject, CollisionFilterGroups.CHARACTER_FILTER, (short)(CollisionFilterGroups.STATIC_FILTER | CollisionFilterGroups.DEFAULT_FILTER));
dynamicsWorld.addAction(character);
It would also be wise to extend the MotionState class to hold the transform
public class MyMotionState extends MotionState {
private Transform worldTransform;
public MyMotionState()
{
worldTransform = new Transform();
worldTransform.setIdentity();
}
#Override
public Transform getWorldTransform(Transform worldTrans)
{
worldTrans.set(worldTransform);
return worldTrans;
}
#Override
public void setWorldTransform(Transform worldTrans)
{
worldTransform.set(worldTrans);
}
}
and linking the Kinematic to a RigidBody for applying the physics to the character, and getting info on rendering.
rigidBody.setCollisionFlags(rigidBody.getCollisionFlags() | CollisionFlags.KINEMATIC_OBJECT);
rigidBody.setActivationState(CollisionObject.DISABLE_DEACTIVATION);
Don't forget to update the physics engine once every iteration of the game loop.
Transform transform = new Transform();
transform.setIdentity();
transform.origin.set(input.getX(), input.getY(), input.getZ());
myMotionState.setWorldTransform(transform);
rigidBody.setCenterOfMassTransform(myMotionState.getWorldTransform());
If you prefer, you could put these in your MainCharacter class or whatever you call it (I like it for the object oriented feel and ease to understand)
public class MainCharacter implements KeyListener, MouseListener
{
private DynamicsWorld world;
private MyMotionState myMotionState;
private RigidBody rigidBody;
private KinematicCharacterController character;
private ConvexShape shape;
private Texture texture;
private GhostObject ghost;
private Vector3f pos;
public MainCharacter(DynamicsWorld world, Vector3f initialPosition, ConvexShape shape, Texture texture)
{
this.world = world;
RigidBodyConstructionInfo constructInfo = new RigidBodyConstructionInfo(...);
this.myMotionState = myMotionState;
rigidBody = new RigidBody(constructInfo);
ghost = new GhostObject();
character = new KinematicCharacterController(ghost,shape,1);
}
public void render()
{
glBegin(GL_QUADS);
glVertex3f(...
...
glEnd();
}
public void mouseMoved(MouseEvent e)
{
//pseudocode
this.yaw = e.getDX();
this.pitch = e.getDY();
}
public void keyPressed(KeyEvent e)
{
Vector3f dPos = null;
if(e.getKeyChar() == 'W')
{
dPos.x = 10;
}
else if(e.getKeyChar() == 'S')
{
dPos.x = -10;
}
etc...
move(dPos.x,dPos.y,dPos.z);
}
public void move(float dx, float dy, float dz) {
pos.z += dx * (float) Math.cos(Math.toRadians(yaw - 90)) + dz * Math.cos(Math.toRadians(yaw));
pos.x -= dx * (float) Math.sin(Math.toRadians(yaw - 90)) + dz * Math.sin(Math.toRadians(yaw));
pos.y += dy * (float) Math.sin(Math.toRadians(pitch - 90)) + dz * Math.sin(Math.toRadians(pitch));
//pseudocode
rigidBody.update(pos);
world.update(pos);
}
}
I hope I have helped you.