为什么使用libgdx的applyLinearImpulse不能工作?

问题描述 投票:0回答:1

我需要一些帮助,当我尝试做一个游戏,它是由命令控制的。我需要使用textarea,并尝试将textarea的值传递给contructer。但是我的游戏不能运行。我知道出现了什么错误,因为我调用了2次contructer。我添加了一些代码。

public class inputs extends Game implements Disposable {
    private Skin skin;
    private Viewport viewport;
    public Stage stage;
    private Table table;
    private TextButton button;
    public TextArea TF;
    private Main game;
    public SpriteBatch spriteBatch;

    public inputs(final SpriteBatch sb, final Main game){

        viewport = new FitViewport(1200, 624, new OrthographicCamera());
        stage = new Stage(viewport, sb);

        skin = new Skin(Gdx.files.internal("data/uiskin.json"));
        button = new TextButton("Send", skin, "default");
        TF = new TextArea("", skin);

        TF.setWidth(300);
        TF.setHeight(570);
        TF.setPosition(0,54);

        button.setWidth(300);
        button.setHeight(54);
        button.setPosition(0, 0);

        button.addListener(new ClickListener(){
            @Override
            public void clicked(InputEvent event, float x, float y) {

                spriteBatch = new SpriteBatch();
                setScreen(new MainCodeProgram(game,TF.getText(),spriteBatch));
                TF.setText("");
                button.setTouchable(Touchable.disabled);
            }
        });
        stage.addActor(TF);
        stage.addActor(button);
        Gdx.input.setInputProcessor(stage);
        Gdx.input.setInputProcessor(stage);
    }
    public void setButtonTouchable(){
        button.setTouchable(Touchable.enabled);
    }

    @Override
    public void create() {

    }

    @Override
    public void dispose() {
        stage.dispose();
    }
}

Main.java :

public class Main extends Game {
    public SpriteBatch spriteBatch;
    public static int Width = 400;
    public static int Height = 208;
    public static final short objectwhit = 32;
    public static final short mariowhit= 2;
    public static final short itemwhit = 256;
    public static float PPM = 100;
    public static final short marioheadwhit = 512;
    public static final short blockwhit = 4;
    public static final short coinwhit = 8;
    public static final short nothing = 0;
    public static final short ground = 1;
    public static final short destroyedwhit = 16;
    public static final short enemywhit = 64;
    public static final short enemyheadwhit = 128;
    public static inputs inp1;


    @Override
    public void create () {
        spriteBatch = new SpriteBatch();
        inp1 = new inputs(spriteBatch,this);
        setScreen(new MainCodeProgram(this,null,spriteBatch));
    }


    @Override
    public void dispose() {
        super.dispose();
        spriteBatch.dispose();
    }


}

Pseudocode recognize :

public class MainCodeProgram extends JFrame implements Screen, TextInputListener, Disposable {
    static ArrayList<String> firstintkint = new ArrayList<String>();
    static ArrayList<Integer> firstintvalue = new ArrayList<Integer>();  //int
    private Main game;
    private OrthographicCamera orthographicCamera;
    private TextureAtlas textureAtlas;
    public static int whichlevel=1;
    private Mario player;
    public Stage stage;
    private Hud hud;
    private TmxMapLoader maploader;
    private TiledMap tilemap;
    static int walks = 0;
    private OrthogonalTiledMapRenderer renderer;
    private Viewport viewport;
    private World world;
    private Array<Item> items;
    private LinkedBlockingQueue<ItemVector> itemstoSpawn;
    String text="";
    private Box2DDebugRenderer b2dr;
    private OtherWorldCreator otherWorldCreator;
    public  String kodas;
    public boolean b =false;


public  MainCodeProgram(){

}
    public MainCodeProgram(Main game, String text,SpriteBatch spriteBatch) {
        if(text == null){
            textureAtlas = new TextureAtlas("All.pack");
            this.game= game;
            orthographicCamera = new OrthographicCamera();
            viewport = new FitViewport(Main.Width / Main.PPM, Main.Height / Main.PPM, orthographicCamera);
            viewport.apply();
            hud = new Hud(game.spriteBatch);
            newlevel();
            otherWorldCreator = new OtherWorldCreator(this);
            player = new Mario( this);
             world.setContactListener(new WorldContact());
            items = new Array<Item>();
            itemstoSpawn = new LinkedBlockingQueue<ItemVector>();
        }

        if(text != null){
            b = true;
            textureAtlas = new TextureAtlas("All.pack");
            this.game= game;
            orthographicCamera = new OrthographicCamera();
            viewport = new FitViewport(Main.Width / Main.PPM, Main.Height / Main.PPM, orthographicCamera);
            viewport.apply();
            hud = new Hud(spriteBatch);
            newlevel();
            otherWorldCreator = new OtherWorldCreator(this);
            player = new Mario( this);
            world.setContactListener(new WorldContact());
            items = new Array<Item>();
            itemstoSpawn = new LinkedBlockingQueue<ItemVector>();
            input(text);

        }

    }

 public TextureAtlas getAtlas(){return textureAtlas;}
    @Override
    public void show() {}
    int i = 0, kur = 1;
    public void handleInput(float dt) {
        if (player.currentstate!= Mario.State.died) {
           ;

        }
    }
    public void spawnItem(ItemVector idef)
    {
        itemstoSpawn.add(idef);
    }
    public void handleSpawningItems(){
        if(!itemstoSpawn.isEmpty())
        {
            ItemVector idef = itemstoSpawn.poll();
            if(idef.type == Mushroom.class){items.add(new Mushroom(this, idef.position.x,idef.position.y));}
        }
    }
    public void update(float dt)
    {
       handleInput(dt);
        handleSpawningItems();
        world.step(1 / 60f, 6, 2);
        player.update(dt);
        for (Enemy enemy: otherWorldCreator.getEbemies()) {
            enemy.update(dt);
            if(enemy.getX() < player.getX() + 224 / Main.PPM){enemy.b2body.setActive(true);}
        }
        for(Item item : items){item.update(dt);}
        hud.refresh(dt);
        if(player.currentstate!= Mario.State.died){orthographicCamera.position.x = player.b2body.getPosition().x;}
        orthographicCamera.update();
        renderer.setView(orthographicCamera);
    }
    public boolean gameOver()
    {
        if(player.currentstate== Mario.State.died && palyer.getStateTimer() > 3){return true;}
        if(whichlevel== 5){return true;}
        else if(player.getY() <0){return true;}
        else{return false;}
    }
    public boolean Youwonn()
    {
        if(whichlevel==4){return true;}
        else{return false;}
    }

    @Override
    public void render(float delta) {
        update(delta);
        int k = 0;
       Gdx.gl.glClearColor(0,0,0,1);
       Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
        renderer.render();
        b2dr.render(world, orthographicCamera.combined);
        game.spriteBatch.setProjectionMatrix(orthographicCamera.combined);
        game.spriteBatch.begin();
        game.draw(game.spriteBatch);
        for (Enemy enemy: otherWorldCreator.getEbemies())
            enemy.draw(game.spriteBatch);
        for(Item item : items)
            item.draw(game.spriteBatch);
        game.spriteBatch.end();
        game.spriteBatch.setProjectionMatrix(hud.stage.getCamera().combined);
        hud.stage.draw();
        if(gameOver())
        {
            whichlevel= 1;
            game.setScreen(new GameOverWorld(game));
            dispose();
        }
        if ((player.getX() > 15 && whichlevel< 4)) {
            whichlevel++;
            if(whichlevel!=4){
                game.setScreen(new MainCodeProgram(game,"",""));    
                dispose();
            }
        }
        if (whichlevel==4)
        {
            game.setScreen(new WinWindow(game));
            dispose();
        }
        Main.inp1.stage.draw();
    }
    @Override
    public void resize(int width, int height) {viewport.update(width,height);}
    public World getWorld(){ return world;}
    public TiledMap getMap(){return tilemap;}
    @Override
    public void pause() {}
    @Override
    public void resume() {}
    @Override
    public void hide() {}
    public  void newlevel()
    {
        maploader = new TmxMapLoader();
        if(whichlevel== 1){tilemap = maploader.load("mario1lvl.tmx");
        }
        if (whichlevel== 2){tilemap = maploader.load("mario2lvl.tmx");}
        if (whichlevel== 3){tilemap = maploader.load("mario3lvl.tmx");}
        if (whichlevel== 4){
            game.setScreen(new WinWindow(game));}


            renderer = new OrthogonalTiledMapRenderer(tilemap, 1  / Main.PPM);

            orthographicCamera.position.set(viewport.getWorldWidth() / 2, viewport.getWorldHeight() / 2, 0);

        world = new World(new Vector2(0, -10 ), true);
        b2dr = new Box2DDebugRenderer();
    }
    @Override
    public void dispose() {
        tilemap.dispose();
        renderer.dispose();
        world.dispose();
        b2dr.dispose();
        hud.dispose();
    }
    public void input(String text) {
        ArrayList<String> pseudocode = new ArrayList<String>();
        this.text = text;
        i = 0;
        String str = text;
        String split[] = str.split("/");
        for (String spacebar : split) {
            pseudocode.add(spacebar);
            i = 0;
        }
        int foras = 0;
        for (int i = 0;i < pseudocode.size(); i++) {
            if(pseudocode.get(i).equals("jump")||pseudocode.get(i).equals("jump;")){jump();}   
            if(pseudocode.get(i).startsWith("int")){recognizeint(pseudocode.get(i));}
            if(pseudocode.get(i).startsWith("for"))
            {
                recognizefor(pseudocode.get(i));
                foras++;
            }
            if(pseudocode.get(i).startsWith("while")){ recognizewhile(pseudocode.get(i));}
            if(pseudocode.get(i).endsWith("--")||pseudocode.get(i).endsWith("--;"))
            {
                if(foras == 0){minuminus(pseudocode.get(i));}
                else{foras--;}
            }
            if(pseudocode.get(i).endsWith("++")||pseudocode.get(i).endsWith("++;"))
            {
                if(foras==0){plusplus(pseudocode.get(i));}
                else{foras--;}
            }
            if(istheend){
                walks = 0;
                istheend = false;
            }
        }
    }

    @Override
    public void canceled() {

    }

 public void jump()
    {
        if(istheend){
            try {Thread.sleep(1*walks);
            } catch (InterruptedException e) {e.printStackTrace();}}
        else{try {Thread.sleep(50*walks);
        } catch (InterruptedException e) {e.printStackTrace();}}
        walks = 0;
        if(player.b2body.getLinearVelocity().y == 0){
            if(b == true) {
                player.b2body.applyLinearImpulse(new Vector2(0, 4f), player.b2body.getWorldCenter(), true);      //Mistake is here
            }
        } 

        else if(player.b2body.getLinearVelocity().y != 0){
            try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}
            player.b2body.applyLinearImpulse(new Vector2(0, 4f), player.b2body.getWorldCenter(), true);
        }
    }
}

错误在这里。

public void jump()
    {
        if(istheend){
            try {Thread.sleep(1*walks);
            } catch (InterruptedException e) {e.printStackTrace();}}
        else{try {Thread.sleep(50*walks);
        } catch (InterruptedException e) {e.printStackTrace();}}
        walks = 0;
        if(player.b2body.getLinearVelocity().y == 0){
            if(b == true) {
                player.b2body.applyLinearImpulse(new Vector2(0, 4f), player.b2body.getWorldCenter(), true);      //Mistake is here
            }
        } 

        else if(player.b2body.getLinearVelocity().y != 0){
            try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}
            player.b2body.applyLinearImpulse(new Vector2(0, 4f), player.b2body.getWorldCenter(), true);
        }
    }

非常感谢你的帮助

java libgdx
1个回答
0
投票

我相信你的代码有点混乱,对于ApplyLinearImpulse的工作,在你的HandleInput中,你发送一个命令jump(),然后在Entity里面你使用jump()方法,并且还使用update(dt)方法+getState()+getFrame()来加入b2body的动画。

你的jump()方法应该是这样简单的

public void jump(){
if(currentState != State.Jumping){
b2body.applyLinearImpulse(new Vector2(0,4f), b2body.getWorldCenter(), true);
currentState=State.JUMPING
}
}

applyLinearImpulse应该卡住的是你包含的条件。尽量全部删除,只留下主要的东西。也可以在所有地方使用LOGS Gdx.app.log("MESSAGE:", "" + variable); 并且你可以开始看到你的方法和变量的进退,并找到你的错误。

另外,如果你想学习更多的知识,并且不要忘记任何关于地图视口b2bodies的细节,请关注我的B2Box教程(Youtube Github),它非常快速和易于操作,你会爱上使用B2Box做任何事情:-),并且继续LibGdx框架的开发。

点击 此处 Youtube教程。

点击 此处 GitHub代码。

希望对你有所帮助。

干杯!

© www.soinside.com 2019 - 2024. All rights reserved.