我正在尝试在游戏中使用touchdown()。动机很简单,我只想基于屏幕上的触摸检测来移动播放器,但它给出了以下错误:
Exception in thread "LWJGL Application" java.lang.NullPointerException
at com.mygdx.game.sprites.Ron.touchDown(Ron.java:39)
at com.badlogic.gdx.backends.lwjgl.LwjglInput.processEvents(LwjglInput.java:329)
at com.badlogic.gdx.backends.lwjgl.LwjglApplication.mainLoop(LwjglApplication.java:215)
at com.badlogic.gdx.backends.lwjgl.LwjglApplication$1.run(LwjglApplication.java:124)
,代码是:
package com.mygdx.game.sprites;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input;
import com.badlogic.gdx.InputAdapter;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.math.Vector3;
import com.badlogic.gdx.utils.viewport.ExtendViewport;
import com.badlogic.gdx.utils.viewport.Viewport;
import com.mygdx.game.Constants;
/**
* Created by Vamsi Rao on 11/9/2016.
*/
public class Ron extends InputAdapter {
private Vector2 position;
private Vector2 velocity;
Vector2 worldClick;
boolean right;
boolean left;
private ExtendViewport viewport;
private Texture ron;
public Ron(int x, int y, ExtendViewport viewport) {
super();
position = new Vector2(x, y);
velocity = new Vector2(Constants.VELOCITY_X, 0);
this.viewport = viewport;
ron = new Texture("ron.png");
}
public boolean touchDown(int screenX, int screenY, int pointer, int button) {
worldClick = viewport.unproject(new Vector2(screenX, screenY));
if (worldClick.x >= viewport.getWorldWidth() / 4) {
right = true;
}
if (worldClick.x < viewport.getWorldWidth() / 4) {
left = true;
}
return true;
}
public Vector2 getPosition() {
return position;
}
public Texture getTexture() {
return ron;
}
public void update(float delta) {
left=false;
right=false;
if (right) {
position.x += delta * velocity.x;
}
if (left) {
position.x -= delta * velocity.x;
}
}
}
我已经在另一个类中设置了Input处理器,该类正在使用Ron类的对象ron(上面显示的类),如下所示:
Gdx.input.setInputProcessor(ron);
答案 0 :(得分:0)
39
行是
worldClick = viewport.unproject(new Vector2(screenX, screenY));
所以NullPointerException
更像是viewport
变量 - 你将它传递给构造函数
public Ron(int x, int y, ExtendViewport viewport) {
...
this.viewport = viewport;
...
因此视口可能会提供null
值。
查看What is a NullPointerException, and how do I fix it?
第二件事是,在这种情况下,使用标志可能不是最好的主意 - 你的代码肯定不太可读,而且你有一个冗余的不必要的代码。
//these lines are almost the same
position.x += delta * velocity.x;
position.x -= delta * velocity.x;
更好的是设置速度的方向向量然后将它与update
中的delta相乘,就像你做的那样
//in your touchdown
if (worldClick.x >= viewport.getWorldWidth() / 4) {
velocity.x *= (velocity.x >= 0) ? 1 : -1;
}
//also add else here - there is always one or another here
else if (worldClick.x < viewport.getWorldWidth() / 4) {
velocity.x *= (velocity.x < 0) ? 1 : -1;
}
//in update
position.x += delta * velocity.x;
你也可以通过这种方式轻松实现变速逻辑(比如当角色改变方向时他慢下来然后开始向后移动...... 等)