java - 为什么使用 libgdx applyLinearImpulse 不起作用?

标签 java libgdx

当我尝试制作由命令控制的游戏时,我需要一些帮助。我需要使用 textarea,并且尝试将值从 textarea 传递给构造函数。但我的游戏无法运行。我知道出现了什么错误,因为我调用了构造器两次。我添加一些代码:

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();
    }


}

伪代码识别:

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);
        }
    }

非常感谢您的帮助

最佳答案

我相信你的代码有点令人困惑,因为ApplyLinearImpulse在你的HandleInput中工作,你发送一个命令jump(),在实体内部你创建jump()方法,并制作动画加入b2body, update(dt) 方法 + getState() + getFrame()。

你的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);,您可以开始查看方法和变量的进出情况,并找出错误。

另外,如果您想了解更多信息并且不要忘记有关 map /视口(viewport)/b2bodies 的任何细节,请按照我用作 B2Box 指南的本教程(Youtube/Github)进行操作,它非常快速且容易跟随,您将会喜欢使用 B2Box 完成所有事情:-) 并继续 LibGdx 框架开发。

点击here YouTube 教程。

点击here GitHub 代码。

希望对你有帮助。

干杯!!

关于java - 为什么使用 libgdx applyLinearImpulse 不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61751468/

相关文章:

java - 每行打印 10 个数字

java - 来自 JNI 的 EXCEPTION_ACCESS_VIOLATION (0xc0000005) JVM?

android - Android 上的 Groovy CompileStatic 打乱了 Groovy Truth

java - Libgdx 相机不工作

java - 从 SurfaceView 和 Canvas 到 libGDX

java - 按键时的 JTable 编辑

java - Json 字符串数组转换为 Java 字符串列表

java - Java 中的 corba 问题

java - 修复寻路代码

java - 建议Libgdx初学者教程?