Hey guys .Am currently trying to develop a game paused state ,with the main view being a frozen /Paused hud screen containing the rootnode scene, and a post view containing a nifty menu,such that if i unpause the game,i resume the frozen game. I tried using appstates to switch between a gamerunningappstate and a pauseappstate but when i switch back to the gamerunningappstate ,the previous progress isnt saved and the game starts over again. Now im not sure if i have to change the way i cleanup ,or i have to clone the rootnode state or whatever ,can i get some clarity on how exactly i use appstates to achieve this.
That all depends on how you have implemented the app state really.
Just called setEnabled(false) on the running app state to pause it. That would work
@zarch ,thanks for the quick reply ,i think i asked too many questions ,but the major question if how do i make my world objects idle and stop the timer and everything so that i can define what happens when i set enabled to false.
I don’t understand the question.
What i meant is how do i temporarily stop spatials in the scene graph so that they remain idle ,while the game is paused ,like how every spatial remains idle in any game when a game is paused ,then they resume from their last positions when the game is unpaused ,i havent found a way to do this so far.
It’s your code that moves the spatials.
We can’t tell you how to disable your code since we don’t know how it is constructed - is everything in AppStates? Are you doing updates in update() or simpleUpdate() that aren’t going through an AppState? Is your game model updated in the render loop or in a separate thread?
The situation is further complicated by the possibility that you might be calling into library code that might be doing the position updates for you.
Essentially, the issue is that a paused state is what a JME-based game will be in unless you actively start writing code to do otherwise, and we don’t know what that code is nor can we tell you what part of your code should be looked at first.
You could start with disabling/commenting out your code until you find what’s moving things.
Disable all your own custom controls and appstates.
Disable particles
Disable playing of sounds (if desired)
Disable animations
Disable bulletappstate (if using physics)
Disable fly cam (if using it)
Disable any mouse/keyboard/sensor events
That’s for a normal scenario, unless you got some pseudo magic moving your stuff around.
Essentially you just return early from the update loop as toolforger was demonstrating, as that’s where the logic comes from (in most cases). You can implement it your own controls/appstates/event listeners pause state, by either having a check if its paused and returning early, or have another layer on top which calls your controls update loop if its not paused.
.Okay ,so i split my GamaeRunningAppstate into three, here is my first of three gameRunningAppStateClasses which initialises the spatials
[java]
public class GameObjects extends AbstractAppState
implements PhysicsCollisionListener,Savable{
AssetManager assetManager;
Node rootNode;
Node guiNode;
boolean running;
DirectionalLight light;
InputManager inputManager;
Camera cam;
GameLogic gameLogic;
String playerName;
AppStateManager stateManager;
BulletAppState physics;
Spatial player;
Spatial enemy;
String carName;
VehicleControl player_con;
VehicleControl enemy_con;
BitmapFont guiFont;
ChaseCamera chase;
BitmapText timeText;
float lap1time=0f,lap2time=0f;
Spatial racingTrack,start;
Geometry finishPoint ,checkPt;
Material arrow_mat;
Box pt,pt1;
RigidBodyControl track_con;
HashSet<String> level=new HashSet<String>();
nextLevelState nextLevel;
boolean setLap;
HashSet<Geometry> checkPt_hs =new HashSet<Geometry>();
HashSet<Geometry> finish_hs =new HashSet<Geometry>();
HashSet<Geometry> enemy_hs=new HashSet<Geometry>();
HashSet<Geometry> enemy_lap=new HashSet<Geometry>();
HashSet<Integer> enemyCheckPoints=new HashSet<Integer>();
HashSet<Integer> playerCheckPoints=new HashSet<Integer>();
Timer timer;
BoundingVolume check_pt_region,finish_region;
float startTime,stopTime,time;
boolean timeRun;
SimpleApplication app;
GameInputs input;
CharacterControl arrow_con;
Trigger next_key=new KeyTrigger(KeyInput.KEY_S);
Trigger pause_key=new KeyTrigger(KeyInput.KEY_P);
Trigger restart=new KeyTrigger(KeyInput.KEY_R);
Trigger exit=new KeyTrigger(KeyInput.KEY_ESCAPE);
Picture one,two,three,go;
boolean lapFinished;
Factory factory;
int enemy_score=0,player_score=0;
VehicleControl cop_con;
boolean gameFinished;
Vector3f velocity;
AmbientLight sun;
int index=0;
String[] car=new String[5];
boolean enemy_reach;
StartScreenControllerState screenState=new StartScreenControllerState();
AutomaticVehicleControl auto;
int gameLevel=0;
ScheduledThreadPoolExecutor executor ;
AmbientLight al;
int defeated;
public GameObjects(){
factory=new Factory();
input=new GameInputs();
timeRun=false;
setLap=false;
enemy_reach=false;
lapFinished=false;
}
@Override
public void initialize(AppStateManager stateManager,Application app) {
super.initialize(stateManager, app);
this.app=(SimpleApplication)app;
this.stateManager=stateManager;
this.rootNode=this.app.getRootNode();
this.assetManager=this.app.getAssetManager();
this.guiNode=this.app.getGuiNode();
this.inputManager=this.app.getInputManager();
this.cam=this.app.getCamera();
this.timer=this.app.getTimer();
this.running=this.stateManager.getState(GameObjects.class).isEnabled();
gameLogic=new GameLogic();
gameLogic.setName(playerName);
car[2]=“Porsche”;
car[0]=“Hummer”;
car[1]=“Sincar”;
car[3]=“Car1”;
executor = new ScheduledThreadPoolExecutor(6);
auto=new AutomaticVehicleControl(executor);
Texture buildings=assetManager.loadTexture(“Textures/Sky/Bright/BrightSky.dds”);
Spatial sky=SkyFactory.createSky(assetManager, buildings, false);
sky.setQueueBucket(RenderQueue.Bucket.Sky);
sky.setCullHint(Spatial.CullHint.Never);
rootNode.attachChild(sky);
physics=this.stateManager.getState(BulletAppState.class);
physics.getPhysicsSpace().addCollisionListener(this);
initScene();
initEnemyCars(car[defeated]);
initPlayer(carName);
initGuiDisplay();
initCheckPoints();
this.stateManager.attach(gameLogic);
start=assetManager.loadModel(“Models/start/start.j3o”);
start.setLocalTranslation(factory.getStartPoint(gameLevel).add(0,5,0));
start.scale(3f);
rootNode.attachChild(start);
}
public int getDefeated(){
return defeated;
}
public void setDefeatedCars(int num){
this.defeated=num;
}
public void setCar(String name){
this.carName=name;
}
public void initPlayer(String car) {
player=factory.getCar(car,assetManager);
player.setName(“player”);
player.setUserData(“level”, gameLevel);
player_con=player.getControl(VehicleControl.class);
player_con.setPhysicsLocation(factory.getStartPoint(gameLevel));
player.addControl(new VehicleControlValues().cloneForSpatial(player));
physics.getPhysicsSpace().add(player_con);
rootNode.attachChild(player);
chase =new ChaseCamera(cam,player,inputManager);
chase.setDefaultDistance(15);
chase.setMaxDistance(20);
chase.setMinDistance(15);
chase.setDefaultHorizontalRotation(FastMath.HALF_PI);
chase.setSmoothMotion(true);
chase.setLookAtOffset(new Vector3f(0,2,0));
chase.setDefaultVerticalRotation(FastMath.INV_PI);
chase.setChasingSensitivity(5);
chase.setTrailingEnabled(true);
}
public void initEnemyCars(String car){
enemy=factory.getCar(car, assetManager);
enemy.setUserData("speed", 800f);
enemy.setName("enemy");
enemy.setUserData("level", gameLevel);
enemy_con=enemy.getControl(VehicleControl.class);
enemy.addControl(new VehicleControlValues().cloneForSpatial(enemy));
physics.getPhysicsSpace().add(enemy_con);
rootNode.attachChild(enemy);
enemy_con.setPhysicsLocation((factory.getStartPoint(gameLevel)).add(8,0,0));
}
public void initScene() {
racingTrack=factory.getTrack(gameLevel,assetManager);
racingTrack.setName(“track”);
track_con=new RigidBodyControl(0.0f);
racingTrack.addControl(track_con);
physics.getPhysicsSpace().add(track_con);
rootNode.attachChild(racingTrack);
light=new DirectionalLight();
rootNode.addLight(light);
al=new AmbientLight();
rootNode.addLight(al);
sun=new AmbientLight();
rootNode.addLight(sun);
}
public void initGuiDisplay(){
guiFont =assetManager.loadFont("Interface/Fonts/VirtualDJ.fnt");
timeText =factory.getText(“time”, cam, guiFont);
guiNode.attachChild(timeText);
one=factory.getPic(“one”, assetManager, cam);
two=factory.getPic(“two”, assetManager, cam);
three=factory.getPic(“three”, assetManager, cam);
go=factory.getPic(“go”, assetManager, cam);
Picture speedo=factory.getPic(“speed”, assetManager, cam);
rootNode.attachChild(speedo);
}
public BoundingVolume getFinish(){
return finish_region;
}
public BoundingVolume getCheckPoint(){
return check_pt_region;
}
public Geometry getCheckPointGeo(){
return checkPt;
}
public Geometry getFinishGeo(){
return finishPoint;
}
public void initCheckPoints(){
pt1 =new Box(new Vector3f(factory.getStartPoint(gameLevel)),46,10,5);
finishPoint=new Geometry(“pt1”,pt1);
Material mat=new Material(assetManager,“Common/MatDefs/Misc/Unshaded.j3md”);
mat.setColor(“Color”, ColorRGBA.Blue);
mat.getAdditionalRenderState().setFaceCullMode(RenderState.FaceCullMode.FrontAndBack);
finishPoint.setMaterial(mat);
rootNode.attachChild(finishPoint);
pt =new Box(factory.getCheckPoint(gameLevel),46,10,5);
checkPt=new Geometry(“pt”,pt);
checkPt.setMaterial(mat);
rootNode.attachChild(checkPt);
check_pt_region=checkPt.getModelBound();
finish_region=finishPoint.getModelBound();
}
public void setName(){
this.playerName=factory.getName();
}
public void setLevel(int level,boolean finished){
this.gameLevel=level;
this.gameFinished=finished;
}
public int getLevel(){
return gameLevel;
}
@Override
public void update(float tpf) {
Vector3f camDir=null;
try {
camDir = executor.submit(new Callable<Vector3f>(){
public Vector3f call() throws Exception {
return cam.getDirection();
}
}).get();
} catch (InterruptedException ex) {
Logger.getLogger(GameObjects.class.getName()).log(Level.SEVERE, null, ex);
} catch (ExecutionException ex) {
Logger.getLogger(GameObjects.class.getName()).log(Level.SEVERE, null, ex);
}
light.setDirection(camDir);
float times=timer.getTimeInSeconds();
if(times>6&×<=7){
rootNode.attachChild(three);
}
if(times>8&×<=9){
rootNode.detachChild(three);
rootNode.attachChild(two);
}
if(times>10&×<=11){
rootNode.detachChild(two);
rootNode.attachChild(one);
}
if(times>12&×<=13){
this.stateManager.attach(input);
rootNode.detachChild(one);
rootNode.attachChild(go);
enemy.addControl(auto.cloneForSpatial(enemy));
}
if(times>13){
rootNode.detachChild(go);
start.rotate(0, FastMath.QUARTER_PI/8f, 0);
}
processTime();
}
public void processTime(){
startTime= timer.getTimeInSeconds()-13f;
if(startTime<60f&&startTime>0){
String act=String.valueOf(startTime);
timeText.setText(“Time “+“00:” +(act.substring(0,act.indexOf(”.”)+2)));
}
if((startTime>60f)&&startTime<120f){
String act=String.valueOf( startTime-60) ;
timeText.setText(“Time “+“01:” +(act.substring(0,act.indexOf(”.”)+2)));
}
if((startTime>120f)&&startTime<180f){
String act= String.valueOf(startTime-120) ;
timeText.setText(“Time “+“02:” +(act.substring(0,act.indexOf(”.”)+2)));
}
if((startTime>180f)&&startTime<240f){
String act=String.valueOf(startTime-180);
timeText.setText(“Time “+“03:” +(act.substring(0,act.indexOf(”.”)+2)));
}
if((startTime>240f)&&startTime<300f){
String act=String.valueOf(startTime-240);
timeText.setText(“Time “+“04:” +(act.substring(0,act.indexOf(”.”)+2)));
}
if((startTime>300f)&&startTime<360f){
String act=String.valueOf(startTime-300);
timeText.setText(“Time “+“05:” +(act.substring(0,act.indexOf(”.”)+2)));
}
}
public String getPlayername(){
return playerName;
}
public void setName(String name){
this.playerName=name;
}
@Override
public void cleanup() {
if(stateManager.hasState(input)){
stateManager.detach(input);
}
cam.setRotation(Quaternion.IDENTITY);
cam.setLocation(Vector3f.ZERO);
try{
physics.getPhysicsSpace().remove(player_con);
physics.getPhysicsSpace().remove(track_con);
physics.getPhysicsSpace().remove(enemy_con);
}
catch (Exception e){
}
physics.getPhysicsSpace().removeCollisionListener(this);
rootNode.removeLight(light);
rootNode.removeLight(al);
rootNode.removeLight(sun);
rootNode.detachAllChildren();
guiNode.detachAllChildren();
executor.shutdown();
super.cleanup();
}
public void setLap1Time(Float time1){
this.lap1time=time1;
}
public void setLap2Time(Float time2){
this.lap2time=time2;
}
public void endStage(boolean finished){
nextLevel=new nextLevelState(finished);
stateManager.detach(this);
nextLevel.setLevel(gameLevel, Math.min(lap1time, lap2time));
nextLevel.setName(playerName,carName);
nextLevel.setDefeated(defeated);
stateManager.attach(nextLevel);
}
public void collision(PhysicsCollisionEvent event) {
AudioNode crash=new AudioNode(assetManager,"Sounds/crash.wav");
crash.setPitch(2f);
crash.setVolume(.25f);
if(event.getNodeA().getName().equals("player")){
crash.playInstance();
}
}
public void write(JmeExporter ex) throws IOException {
OutputCapsule outPut=ex.getCapsule(this);
outPut.write(Math.min(lap1time, lap2time), playerName, 0);
}
public void read(JmeImporter im) throws IOException {
InputCapsule inPut=im.getCapsule(this);
inPut.readFloat(playerName,0);
}
}
[/java]
And here is the second class
[java];
class GameLogic extends AbstractAppState
implements ActionListener,ScreenController{
private Node rootNode,guiNode;
private AppStateManager stateManager;
private InputManager inputManager;
private AssetManager assetManager;
private SimpleApplication app;
private VehicleControl player_con;
private VehicleControl enemy_con;
private Camera cam;
String playerName;
int count;
NiftyJmeDisplay niftyDisplay ;
ViewPort niftyView;
Nifty nifty;
BulletAppState physics;
Spatial player;
Spatial enemy;
int position;
Vector3f playerloc = null;
Vector3f player_target=new Vector3f();
GameObjects gameObjects;
float speed=0,lap1time=0f,lap2time=0f;
Spatial racingTrack; ;
RigidBodyControl track_con;
nextLevelState nextLevel;
boolean setLap=false;
List<Geometry>checkPoints=new ArrayList<Geometry>();
HashSet<Geometry> lap1PlayerPoints =new HashSet<Geometry>();
HashSet<Geometry> lap2PlayerPoints =new HashSet<Geometry>();
HashSet<Geometry> lap1EnemyPoints =new HashSet<Geometry>();
HashSet<Geometry> lap2EnemyPoints =new HashSet<Geometry>();
Timer timer;
float startTime,stopTime,time;
boolean timeRun;
GameInputs input;
int enemiesDefeated=0;
Trigger next_key=new KeyTrigger(KeyInput.KEY_S);
Trigger pause_key=new KeyTrigger(KeyInput.KEY_P);
Trigger restart=new KeyTrigger(KeyInput.KEY_R);
Trigger exit=new KeyTrigger(KeyInput.KEY_ESCAPE);
Picture one,two,three,go;
boolean lapFinished=false;
Factory factory;
int player_score=0;
int enemy_score=0;
String[] car=new String[5];
boolean gameFinished,reached;
Vector3f enemy_location;
BitmapFont guiFont;
BitmapText speedText ,timeText,locText,countText,lapText,posText,ptText;
int player_index=0;
boolean enemy_reach=false;
int enemy_index=0;
MotionPath path;
StartScreenControllerState screenState=new StartScreenControllerState();
int gameLevel=0;
Vector3f enemy_dir;
Vector3f enemy_target;
int defeated=0;
MotionPaths paths=new MotionPaths();
ScheduledThreadPoolExecutor executor ;
boolean moving;
@Override
public void initialize(AppStateManager stateManager,Application app){
super.initialize(stateManager, app);
this.app=(SimpleApplication)app;
this.stateManager=stateManager;
this.cam=this.app.getCamera();
this.rootNode=this.app.getRootNode();
this.guiNode=this.app.getGuiNode();
this.assetManager=this.app.getAssetManager();
this.timer=this.app.getTimer();
this.inputManager=this.app.getInputManager();
gameObjects=this.stateManager.getState(GameObjects.class);
factory=new Factory();
this.gameLevel=gameObjects.getLevel();
path=paths.getPath(gameLevel);
car[1]=“Porsche”;
car[2]=“AudiR8”;
car[3]=“Bugatti”;
car[0]=“Car1”;
path=paths.getPath(gameLevel);
guiFont =assetManager.loadFont(“Interface/Fonts/VirtualDJ.fnt”);
locText =factory.getText("lap", cam, guiFont);
guiNode.attachChild(locText);
lapText =factory.getText("laptime", cam, guiFont);
guiNode.attachChild(lapText);
countText =factory.getText("count", cam, guiFont);
guiNode.attachChild(countText);
posText=factory.getText("position", cam, guiFont);
guiNode.attachChild(posText);
ptText =factory.getText("points", cam, guiFont);
guiNode.attachChild(ptText);
executor = new ScheduledThreadPoolExecutor(11);
initPositions();
buildCheckPoints();
initKeys();
}
public void initKeys(){
inputManager.addMapping(“pause”, pause_key);
inputManager.addListener(this, “pause”);
inputManager.addMapping(“restart”, restart);
inputManager.addListener(this, “restart”);
inputManager.addMapping(“exit”, exit);
inputManager.addListener(this, “exit”);
}
public void buildCheckPoints(){
Box[]b=new Box[path.getNbWayPoints()];
for(int j=0;j<path.getNbWayPoints();j++){
b[j]= new Box(path.getWayPoint(j),40,5,40);
checkPoints.add(j,new Geometry(“Geo”+j,b[j]));
}
}
public void initPositions(){
if(rootNode!=null){
rootNode.depthFirstTraversal(new SceneGraphVisitor(){
public void visit(Spatial spat) {
if(spat.getName().equals("player")){
player=spat;
player_con=spat.getControl(VehicleControl.class);
}
if(spat.getName().equals("enemy")){
enemy=spat;
enemy_con=spat.getControl(VehicleControl.class);
}
}
});
}
player_target=getPlayerTarget();
enemy_target=getEnemyTarget();
}
public void setLap1Time(Float time1){
if(!lapFinished) {
this.lap1time=time1;
}
lapFinished=true;
}
public void setLap2Time(Float time2){
if(!setLap) {
this.lap2time=time2;
}
setLap=true;
}
public float getLap1Time(){
return lap1time;
}
public float getLap2Time(){
return lap2time;
}
public Vector3f getPlayerTarget(){
Vector3f pt=null;
try {
pt= executor.submit(new Callable<Vector3f>(){
public Vector3f call() throws Exception {
return path.getWayPoint(player_index);
}
}).get();
} catch (InterruptedException ex) {
Logger.getLogger(GameLogic.class.getName()).log(Level.SEVERE, null, ex);
} catch (ExecutionException ex) {
Logger.getLogger(GameLogic.class.getName()).log(Level.SEVERE, null, ex);
}
return pt;
}
public Vector3f getEnemyTarget(){
Vector3f pt=null;
try {
pt= executor.submit(new Callable<Vector3f>(){
public Vector3f call() throws Exception {
return path.getWayPoint(enemy_index);
}
}).get();
} catch (InterruptedException ex) {
Logger.getLogger(GameLogic.class.getName()).log(Level.SEVERE, null, ex);
} catch (ExecutionException ex) {
Logger.getLogger(GameLogic.class.getName()).log(Level.SEVERE, null, ex);
}
return pt;
}
public boolean gameFinished(){
return gameFinished;
}
public void setName(String name){
this.playerName=name;
}
public void upDatePlayerCheckPoints(){
BoundingVolume checkRadius=checkPoints.get(player_index).getModelBound();
if(checkRadius.contains(getVehicleLocation())){
if(player_index==path.getNbWayPoints()-1){
player_index=0;
++player_score;
}
else if(player_index!=path.getNbWayPoints()-1){
++player_score;
++player_index;
}
}
player_target=getPlayerTarget();
}
public void upDateEnemyCheckPoints(){
try{
enemy_location=(executor.submit(new Callable<Vector3f>(){
public Vector3f call() throws Exception {
return enemy_con.getPhysicsLocation();
}
}).get());
}
catch(Exception x){
}
BoundingVolume checkRadius=checkPoints.get(enemy_index).getModelBound();
if(checkRadius.contains(enemy_location)){
if(enemy_index==path.getNbWayPoints()-1){
enemy_index=0;
++enemy_score;
}
else if(enemy_index!=path.getNbWayPoints()-1){
++enemy_index;
++enemy_score;
}
}
enemy_target=getEnemyTarget();
}
public void upDatePositions(){
if(player_score>enemy_score){
position=1;
}
if(player_score<enemy_score){
position=2;
}
if(player_score==enemy_score){
float player_distance=getPlayerTarget().subtract(getVehicleLocation()).length();
float enemy_distance=enemy_location.subtract(getEnemyTarget()).length();
if(player_distance>enemy_distance){
position=2;
}
if(player_distance<enemy_distance){
position=1;
}
}
posText.setText(“pos “+position+”/2”);
}
@Override
public void setEnabled(boolean enabled) {
super.setEnabled(enabled);
}
@Override
public void update(float tpf){
if (this.app.getTimer().getTimeInSeconds()>13){
}
upDatePlayerCheckPoints();
upDateEnemyCheckPoints();
upDatePositions();
try {
upDateLaps();
} catch (Exception ex) {
Logger.getLogger(GameLogic.class.getName()).log(Level.SEVERE, null, ex);
}
ptText.setText("CheckPoints Cleared"+"\nRhymez "+enemy_score+"\n"+playerName+" "+player_score);
}
public Vector3f getVehicleLocation(){
Vector3f location=null;
try{
location =executor.submit(new Callable<Vector3f>(){
public Vector3f call() throws Exception {
return player_con.getPhysicsLocation();
}
}).get();
}
catch(Exception ex){
}
return location;
}
private void upDateLaps() throws Exception {
if(player_score==path.getNbWayPoints()){
locText.setText(“Lap2/2”);
setLap1Time(timer.getTimeInSeconds()-13);
lapText.setText(“Lap1 time”+factory.convertToMinutes(lap1time));
}
if(player_score==(2*(path.getNbWayPoints()))){
stateManager.detach(input);
player_con.brake(100);
setLap2Time(timer.getTimeInSeconds()-13-lap1time);
lapText.setText("Lap1 time "+factory.convertToMinutes(lap1time)+
"\nLap2 time "+factory.convertToMinutes(lap2time));
gameObjects.setLap1Time(lap1time);
gameObjects.setLap2Time(lap2time);
if(position==1){
inputManager.addMapping("next", next_key);
inputManager.addListener(this,“next”);
if(defeated<4) {
countText.setText(“Press s to go to\n next opponent”);
}
if(defeated==4) {
countText.setText(“Press s to go to\n next track”);
}
}
else if(position==2){
countText.setText(“lost press r to retry”);
}
}
}
@Override
public void cleanup(){
inputManager.removeListener(this);
if(stateManager.hasState(input)){
stateManager.detach(input);
}
guiNode.detachAllChildren();
executor.shutdown();
this.lapFinished=false;
this.setLap=false;
}
public void onAction(String name, boolean isPressed, float tpf) {
if ((name.equals("next"))&&(!isPressed)) {
stateManager.detach(this);
gameObjects.endStage(true);
}
if ((name.equals("pause"))&&(!isPressed)) {
pauseGame();
}
if(name.equals("restart")){
gameObjects.endStage(false);
}
if(name.equals("exit")){
try{
stateManager.detach(this);
stateManager.attach(screenState);
}
catch(Exception ex){
}
}
}
public void resumeGame(){
nifty.exit();
niftyView.removeProcessor(niftyDisplay);
setEnabled(true);
}
public void pauseGame(){
setEnabled(false);
niftyView=this.app.getRenderManager().createPostView(“pause”, cam);
niftyDisplay = new NiftyJmeDisplay(assetManager,inputManager,this.app.getAudioRenderer(),niftyView);
nifty=niftyDisplay.getNifty();
nifty.fromXml(“Interface/Nifty/pauseScreen.xml”, “start”,this);
niftyView.addProcessor(niftyDisplay);
}
public void bind(Nifty nifty, Screen screen) {
}
public void onStartScreen() {
}
public void onEndScreen() {
}
}
[java];
and the last one
[java]
public class GameInputs extends AbstractAppState
implements ActionListener{
SimpleApplication app;
float brakeForce =100.0f,accelerationForce=800.0f,reverseValue=0,steeringValue=0,accelerationValue=0;
InputManager inputManager;
AssetManager assetManager;
AudioNode shift,engine,brake,acc,start;
VehicleControl car_con;
Node rootNode,guiNode;
ScheduledThreadPoolExecutor executor;
Vector3f target;
int index=0;
Factory factory;
BitmapText speedText;
BitmapFont guiFont;
boolean reached=false;
int level;
AppStateManager stateManager;
boolean moving=false;
MotionPath path;
Trigger acc_key=new JoyAxisTrigger(0,JoyInput.AXIS_POV_Y,true);
Trigger back_key=new JoyAxisTrigger(0,JoyInput.AXIS_POV_Y,false);
Trigger left_but=new JoyAxisTrigger(0,JoyInput.AXIS_POV_X,false);
Trigger right_but=new JoyAxisTrigger(0,JoyInput.AXIS_POV_X,true);
MotionPaths paths=new MotionPaths();
@Override
public void initialize(AppStateManager stateManager, Application app) {
super.initialize(stateManager, app);
this.app=(SimpleApplication)app;
this.stateManager=stateManager;
this.assetManager=this.app.getAssetManager();
this.inputManager=this.app.getInputManager();
this.rootNode=this.app.getRootNode();
this.guiNode=this.app.getGuiNode();
factory=new Factory();
executor=new ScheduledThreadPoolExecutor(3);
if(rootNode!=null){
rootNode.depthFirstTraversal(new SceneGraphVisitor(){
public void visit(Spatial spatial){
if(spatial.getName()!=null){
if(spatial.getName().equals(“player”)){
car_con=spatial.getControl(VehicleControl.class);
level=spatial.getUserData(“level”);
}
}
}
});
}
path=paths.getPath(level);
if(path!=null){
try {
doMove(path.getWayPoint(index));
} catch (InterruptedException ex) {
Logger.getLogger(GameInputs.class.getName()).log(Level.SEVERE, null, ex);
} catch (ExecutionException ex) {
Logger.getLogger(GameInputs.class.getName()).log(Level.SEVERE, null, ex);
}
}
setUpInput();
guiFont =assetManager.loadFont("Interface/Fonts/VirtualDJ.fnt");
speedText =factory.getText("speed", this.app.getCamera(), guiFont);
guiNode.attachChild(speedText);
}
public Vector3f getLocation() throws InterruptedException, ExecutionException{
Vector3f loc;
loc=executor.submit(new Callable<Vector3f>(){
public Vector3f call() throws Exception {
return car_con.getPhysicsLocation();
}
}).get();
return loc;
}
public Float getSpeed(){
float velocity=0f;
try{
velocity=executor.submit(new Callable<Float>(){
public Float call() throws Exception {
return car_con.getCurrentVehicleSpeedKmHour();
}
}).get();
}
catch(Exception e){
}
return velocity;
}
@Override
public void update(float tpf) {
float speed=getSpeed();
if(speed>=8){
engine.play();
}else
{
engine.stop();
}
speedText.setText(""+factory.roundOff(speed));
Vector3f dir = null;
try {
dir = target.subtract(getLocation());
} catch (InterruptedException ex) {
Logger.getLogger(GameInputs.class.getName()).log(Level.SEVERE, null, ex);
} catch (ExecutionException ex) {
Logger.getLogger(GameInputs.class.getName()).log(Level.SEVERE, null, ex);
}
if(index==path.getNbWayPoints()-1){
index=0;
}
if(dir.length()<=15){
nextWayPt(true);
try {
moving=false;
target=executor.submit(new Callable<Vector3f>(){
public Vector3f call() throws Exception {
return path.getWayPoint(index);
}
}).get();
} catch (InterruptedException ex) {
Logger.getLogger(GameInputs.class.getName()).log(Level.SEVERE, null, ex);
} catch (ExecutionException ex) {
Logger.getLogger(GameInputs.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
public void nextWayPt(boolean reache){
reached=reache;
if(reached){
++index;
}
reached=false;
}
public void doMove(Vector3f location) throws InterruptedException, ExecutionException{
this.target=location;
if(target!=null||car_con!=null){
Vector3f dir=target.subtract(getLocation());
if(dir.length()>25){
moving=true;
}
}
}
public void setUpInput(){
inputManager.addMapping(“sright”, new KeyTrigger(KeyInput.KEY_D));
inputManager.addMapping(“sleft”, new KeyTrigger(KeyInput.KEY_A));
inputManager.addMapping(“acc”, new KeyTrigger(KeyInput.KEY_UP),acc_key);
inputManager.addMapping(“brake”, new KeyTrigger(KeyInput.KEY_DOWN),back_key);
inputManager .addMapping(“left”, new KeyTrigger(KeyInput.KEY_LEFT),left_but);
inputManager.addMapping(“right”, new KeyTrigger(KeyInput.KEY_RIGHT),right_but);
inputManager.addMapping(“reset”, new KeyTrigger(KeyInput.KEY_SPACE));
inputManager.addMapping(“reverse”, new KeyTrigger(KeyInput.KEY_RSHIFT));
inputManager.addListener(this, new String[]{
“acc”,“brake”,“left”,“right”,“reset”,“reverse”,“sleft”,“sright”
});
brake =new AudioNode(assetManager,"Sounds/Brake.wav");
shift =new AudioNode(assetManager,"Sounds/turn1.wav");
shift.setLooping(true);
engine =new AudioNode(assetManager,"Sounds/sports car engine.wav");
engine.setLooping(true);
}
public void onAction(String name, boolean isPressed, float tpf) {
if(name.equals(“left”)){
if(isPressed) {
steeringValue +=.2f;
shift.play();
} else {
shift.stop();
steeringValue -=.2f;
}
car_con.steer(steeringValue);
}
if(name.equals(“right”)){
if(isPressed) {
shift.play();
steeringValue -=.2f;
} else {
shift.stop();
steeringValue +=.2f;
}
car_con.steer( steeringValue);
}
if(name.equals(“brake”)){
if(isPressed) {
car_con.brake(brakeForce);
brake.play();
} else {
car_con.brake(0);
brake.stop();
}
}
if(name.equals(“acc”)){
if(isPressed) {
accelerationValue +=accelerationForce;
engine.setVolume(10f);
} else {
accelerationValue -=accelerationForce;
engine.setVolume(1f);
}
car_con.accelerate(accelerationValue);
}
if(name.equals(“reset”)){
if(isPressed){
car_con.setPhysicsLocation(path.getWayPoint(index));
car_con.setAngularVelocity(Vector3f.ZERO);
car_con.resetSuspension();
car_con.setPhysicsRotation(Matrix3f.IDENTITY);
car_con.setLinearVelocity(Vector3f.ZERO);
}
}
if(name.equals(“reverse”)){
car_con.setLinearVelocity(Vector3f.ZERO);
if(isPressed){
reverseValue-=200;
}
else{
reverseValue+=200;
}
car_con.accelerate(reverseValue);
}
if(name.equals(“sleft”)){
if(isPressed) {
steeringValue +=.5f;
shift.play();
} else {
shift.stop();
steeringValue -=.5f;
}
car_con.steer(steeringValue);
}
if(name.equals(“sright”)){
if(isPressed) {
shift.play();
steeringValue -=.5f;
} else {
shift.stop();
steeringValue +=.5f;
}
car_con.steer(steeringValue);
}
}
@Override
public void cleanup() {
brake.stop();
executor.shutdown();
engine.stop();
shift.stop();
car_con.brake(brakeForce);
inputManager.removeListener(this);
super.cleanup();
//TODO: cle;an up what you initialized in the initialize method,
//e.g. remove all spatials from rootNode
//this is called on the OpenGL thread after the AppState has been detached
}
}
[java]
some of the methods in the code are probably not relevant like the nifty if the gameLogic class ,cause i was thinking way outside the box the figure something out.
And here is another custom control which runs with the gamerunning appstates
[java]
public class AutomaticVehicleControl extends AbstractControl
implements PhysicsCollisionListener{
private VehicleControl vehicle;
float speed=800;
float steer=0;
private SimpleApplication app;
float accelerate=0;
private HashSet<Integer>laps=new HashSet<Integer>();
List<Geometry> checkPoints=new ArrayList<Geometry>();
private Vector3f targetLocation=new Vector3f();
private Vector3f currentLocation=new Vector3f();
private Vector3f targetDirection=new Vector3f();
private Vector3f forwardDirection=new Vector3f();
private Vector3f vector4=new Vector3f();
private Vector3f aimDirection=new Vector3f(Vector3f.UNIT_Z);
private Plane plane=new Plane();
int level;
Factory factory=new Factory();
int index=0;
boolean reached=false;
private MotionPath path;
ScheduledThreadPoolExecutor executor;
static final Quaternion ROTATE_RIGHT=new Quaternion().fromAngleAxis(FastMath.HALF_PI, Vector3f.UNIT_Y);
private boolean moving=false;
GameObjects game;
public AutomaticVehicleControl(ScheduledThreadPoolExecutor exe){
executor=exe;
}
public void buildTargets(){
Box box[]=new Box[path.getNbWayPoints()];
for(int i=0;i<path.getNbWayPoints();i++){
box[i]=new Box(path.getWayPoint(i),10,5,10);
checkPoints.add(i,new Geometry(“Geo”+i,box[i]));
}
}
public void doMove(Vector3f location){
targetLocation.set(location);
try {
currentLocation.set(getLocation());
} catch (InterruptedException ex) {
Logger.getLogger(AutomaticVehicleControl.class.getName()).log(Level.SEVERE, null, ex);
} catch (ExecutionException ex) {
Logger.getLogger(AutomaticVehicleControl.class.getName()).log(Level.SEVERE, null, ex);
}
BoundingVolume checkRadius=checkPoints.get(index).getModelBound();
if(!checkRadius.contains(currentLocation)){
moving=true;
}
}
public void setIndex(int idex){
this.index=idex;
}
public Integer getIndex(){
return this.index;
}
@Override
public void setSpatial(Spatial spatial){
this.spatial=spatial;
if(spatial==null){
return;}
this.level=spatial.getUserData(“level”);
MotionPaths paths=new MotionPaths();
path=paths.getPath(level);
Float spatialSpeed=(Float)spatial.getUserData(“speed”);
if(spatialSpeed!=null){
this.speed=spatialSpeed;
}
buildTargets();
vehicle=spatial.getControl(VehicleControl.class);
doMove(path.getWayPoint(index));
vehicle.getPhysicsSpace().addCollisionListener(this);
game=new GameObjects();
}
public boolean isMoving(){
return moving;
}
public Vector3f getTargetLocation(){
return targetLocation;
}
public Vector3f getLocation() throws InterruptedException, ExecutionException{
return executor.submit(new Callable<Vector3f>(){
public Vector3f call() throws Exception {
return vehicle.getPhysicsLocation();
}
}).get();
}
public Vector3f getForwardVector() throws InterruptedException, ExecutionException{
return executor.submit(new Callable<Vector3f>(){
public Vector3f call() throws Exception {
return vehicle.getForwardVector(forwardDirection);
}
}).get();
}
@Override
public void setEnabled(boolean enabled){
this.enabled=enabled;
}
@Override
public boolean isEnabled(){
return enabled;
}
@Override
protected void controlUpdate(float tpf) {
if(!moving){
return;
}
if(!enabled){
moving=false;
}
try {
currentLocation=getLocation();
} catch (InterruptedException ex) {
Logger.getLogger(AutomaticVehicleControl.class.getName()).log(Level.SEVERE, null, ex);
} catch (ExecutionException ex) {
Logger.getLogger(AutomaticVehicleControl.class.getName()).log(Level.SEVERE, null, ex);
}
targetDirection.set(targetLocation.subtract(currentLocation));
BoundingVolume checkRadius=checkPoints.get(index).getModelBound();
if(checkRadius.contains(currentLocation)){
if(index==path.getNbWayPoints()-1){
if(laps.isEmpty()){
index=0;
doMove(path.getWayPoint(index));
laps.add(level);
}
else if(!laps.isEmpty()){
index=0;
vehicle.accelerate(0);
vehicle.brake(1000);
moving=false;
laps.clear();
}
}
else if(index!=(path.getNbWayPoints()-1)){
++index;
doMove(path.getWayPoint(index));
}
}
else {
targetDirection.normalizeLocal();
try {
forwardDirection=getForwardVector().normalizeLocal();
} catch (Exception ex) {
Logger.getLogger(AutomaticVehicleControl.class.getName()).log(Level.SEVERE, null, ex);
}
vector4.set(forwardDirection);
ROTATE_RIGHT.multLocal(vector4);
plane.setOriginNormal(spatial.getWorldTranslation(), vector4);
float angle= 1-forwardDirection.dot(targetDirection);
float anglemult=FastMath.QUARTER_PI;
float speedmult=.9f;
if(plane.whichSide(targetLocation)==Plane.Side.Negative){
anglemult*=-1;
}
if(angle>1f){
speedmult*=-1;
anglemult*=-1;
angle=1f;
}
accelerate=speed*speedmult;
vehicle.steer(angle*anglemult);
vehicle.accelerate(accelerate);
vehicle.brake(0);
}
if(vehicle.getLinearVelocity().getY()>10||vehicle.getLinearVelocity().getY()<-10)
{
vehicle.setPhysicsLocation(path.getWayPoint(index));
vehicle.setAngularVelocity(Vector3f.ZERO);
vehicle.resetSuspension();
vehicle.setPhysicsRotation(Matrix3f.IDENTITY);
vehicle.setLinearVelocity(Vector3f.ZERO);
}
if(!this.enabled){
}
}
@Override
protected void controlRender(RenderManager rm, ViewPort vp) {
//Only needed for rendering-related operations,
//not called when spatial is culled.
}
@Override
public void read(JmeImporter im) throws IOException {
super.read(im);
InputCapsule in = im.getCapsule(this);
//TODO: load properties of this Control, e.g.
//this.value = in.readFloat("name", defaultValue);
}
@Override
public void write(JmeExporter ex) throws IOException {
super.write(ex);
OutputCapsule out = ex.getCapsule(this);
//TODO: save properties of this Control, e.g.
//out.write(this.value, "name", defaultValue);
}
public void collision(PhysicsCollisionEvent event) {
if((event.getNodeA().getName().equals("enemy"))&&(event.getNodeB().getName().equals("track"))){
if(vehicle.getCurrentVehicleSpeedKmHour()<3&&vehicle.getCurrentVehicleSpeedKmHour()>-3){
vehicle.setPhysicsLocation(path.getWayPoint(index));
vehicle.setAngularVelocity(Vector3f.ZERO);
vehicle.resetSuspension();
vehicle.setPhysicsRotation(Matrix3f.IDENTITY);
vehicle.setLinearVelocity(Vector3f.ZERO);
}
}
}
public Control cloneForSpatial(Spatial spatial) {
AutomaticVehicleControl control=new AutomaticVehicleControl(executor);
control.setSpatial(spatial);
return control;
}
}
[/java]
tl;dr
Try making a SSCCE (see sscce.org for an explanation).
A SSCCE isn’t really going to help here though, as it’s not that something it’s going wrong - it’s that he doesn’t know how to do something.
Really we can’t help you here. Your code is moving the objects. Somehow you need to turn off that moving.
Whether that is by disabling those app states, checking flags, or whatever - that’s your call as the person designing and coding your game.
P.S. Really this is showing an architectural hole though.
You should really be thinking of a model-view-controller architecture.
Pausing a game pauses the model, the view though keeps running as usual but because the model is paused the view no longer moves either.
Hurray !!! ,i finally got the game to pause ,@wezrule ,your advice was pretty straight forward , i used
[java]
public void setEnabled(boolean enabled) {
super.setEnabled(enabled);
auto_con=enemy.getControl(AutomaticVehicleControl.class);
if(!enabled){
input.setEnabled(enabled);
physics.setEnabled(enabled);
physics.getPhysicsSpace().removeCollisionListener(this);
auto_con.setEnabled(enabled);
stateManager.getState(GameObjects.class).setEnabled(enabled);
}
else if(enabled){
input.setEnabled(enabled);
physics.setEnabled(enabled);
physics.getPhysicsSpace().addCollisionListener(this);
auto_con.setEnabled(enabled);
stateManager.getState(GameObjects.class).setEnabled(enabled);
}
}
[/java]
and the game could pause and unpause upon pressing the pause key, thanks for the great help guys.