Libgdx box2d тело застряло - PullRequest
       6

Libgdx box2d тело застряло

0 голосов
/ 29 декабря 2018

Я создаю игру с libgdx и box2d и сейчас создал тело прямоугольника.Тело - это «блок», который игрок может бросить, чтобы попытаться заблокировать мяч.

Проблема, с которой я столкнулся, заключается в том, что тело застряло в позиции (0, 47,5184), даже если этоне то место, где оно было установлено.Я даже могу установить положение на что-то сумасшедшее, например (-10000, -10000), и оно все равно будет рендериться в (0, 47.5184).

Прямоугольник по-прежнему отлично работает с броском, но он просто начинается не в том месте и не может быть изменен.

В моем коде я создаю тело, вызывая методы createBlock и setBlockProperties.Эти методы вызываются в функции «show». Также обратите внимание, что используемый для игры мяч был создан точно так же и работает нормально.

Код:

public class GameScreen extends ScreenAdapter {
    Controller game;

    public World world;
    public Body ball;
    public Body block;
    public Box2DDebugRenderer box2DDebugRenderer;
    private Matrix4 cameraBox2D;

    public MyGestureListener myGestureListener;

    //x-axis length for top/bottom bar
    private float goalWidth;

    //pixels per meter
    public float PPM;

    //y-axis height for back bar
    private float goalHeight;
    private float goalPostThickness;

    //Screen height and width
    private float screenWidth;
    private float screenHeight;

    //How far down/up posts are from edge of screen
    private float goalPostTopOffset;
    private float goalPostBottomOffset;

    //Center x,y of cannon
    private float cannonOriginX; //Variables used for starting poisition of balls
    private float cannonOriginY;

    //Center x,y of ball
    float ballX;
    float ballY;

    //Velocity of ball
    public float velocity = 50;

    //Tracks users drag y coord
    public float panLocation = 0;

    //Velocity of block once the user releases
    public float flingVelocity;

    //Changes to true when the block is released
    public boolean isReleased = false;

    public GameScreen (Controller game){
        this.game = game;
    }

    @Override
    public void show(){

        myGestureListener = new MyGestureListener(game, this);
        cameraBox2D = new Matrix4(game.cam.combined);

        screenWidth = game.getScreenWidth();
        screenHeight = game.getScreenHeight();

        PPM = screenHeight / 80;

        goalPostTopOffset = screenHeight/7;
        goalPostBottomOffset = goalPostTopOffset * 3;
        goalHeight = screenHeight - (goalPostTopOffset + goalPostBottomOffset);
        goalWidth = screenWidth / 6;
        goalPostThickness = screenWidth / 75;

        cannonOriginX = goalWidth / 2; //Variables used for starting position of balls
        cannonOriginY = (goalPostThickness*5) / 2;

        ballX = 0 + cannonOriginX;
        ballY = (goalPostBottomOffset - (goalPostBottomOffset / 4)) + cannonOriginY;

        world = new World(new Vector2(0, 0f), true);
        box2DDebugRenderer = new Box2DDebugRenderer();

        //Creates animated ball
        ball = createBall();

        //Sets radius, density, etc.
        setBallProperties(ball);

        //Creates block that stops balls
        block = createBlock();

        //Sets properties
        setBlockProperties(block);
    }

    @Override
    public void render(float delta){
        //Logic
        world.step(1/60f, 6, 2);

        //Draw
        game.cam.update();
        Gdx.gl.glClearColor(0, 0, 0, 0);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

        box2DDebugRenderer.render(world, game.cam.combined.scl(PPM));
        game.shape.setProjectionMatrix(game.cam.combined);

        Gdx.input.setInputProcessor(new GestureDetector(myGestureListener));

        System.out.println(block.getPosition().y);
        System.out.println(block.getPosition().x);

        drawNonAnimated();
        drawAnimated();


//show()
        cameraBox2D = game.cam.combined.cpy(); //Copy the main camera
        cameraBox2D.scl(PPM); //Scale the camera projection to the ratio you're using for Box2D

//render()
        box2DDebugRenderer.render(world, cameraBox2D);
    }

    @Override
    public void hide(){

    }

    //draws stationary objects such as goal posts
    public void drawNonAnimated(){


        //Cannon platform
        game.shape.setColor(1, 1, 1, 1);
        game.shape.begin(ShapeRenderer.ShapeType.Filled);
        game.shape.rect(0, (goalPostBottomOffset - (goalPostBottomOffset / 4))/PPM, goalWidth/PPM, (goalPostThickness*2)/PPM);
        game.shape.end();

        //Cannon
        game.shape.setColor(1, 1, 1, 1);
        game.shape.begin(ShapeRenderer.ShapeType.Filled);
        game.shape.rect(0, (goalPostBottomOffset - (goalPostBottomOffset / 4))/PPM, cannonOriginX/PPM,
                cannonOriginY/PPM, goalWidth/PPM, (goalPostThickness*5)/PPM, 1, 1, 45);
        game.shape.end();
    }

    public void drawAnimated(){
        //FOR BALL
        velocity--;
        ball.setLinearVelocity(new Vector2(35,velocity));

        Vector2 pos = ball.getPosition();

        if (pos.x >= screenWidth/PPM){
            ball.setTransform(new Vector2(ballX/PPM, ballY/PPM), 0);
            //max 75   min 50

            velocity = randInt(50, 75);
        }

        //Attaching a regular libgdx shape to the position of box2d shape
        game.circle.setColor(1, 1, 1, 1);
        game.circle.begin(ShapeRenderer.ShapeType.Filled);
        game.circle.circle(pos.x*PPM, pos.y*PPM, goalPostThickness * 1.5f);
        game.circle.end();
        game.cam.update();

        blockerMovement();
    }

    public void blockerMovement(){
        //FOR BLOCKER RECTANGLE ANIMATION
        Vector2 pos = block.getPosition();
        float boundaryLocation = (goalPostBottomOffset - (goalPostBottomOffset / 4))/PPM;
        //attachBlockerShape(pos);

        panLocation = myGestureListener.getPanLocation();
        if (isReleased == true){
            //Get the velocity as the block is released
            //to determine the speed it will continue to go after release
            block.setLinearVelocity(0, flingVelocity);
            flingVelocity -= 3;
        }

        else if (myGestureListener.getCheckRelease()|| panLocation/PPM >= boundaryLocation && !isReleased) {
            flingVelocity = myGestureListener.speed;
            isReleased = true;
            System.out.println("SPEED: " + flingVelocity);
        }
        else {

            block.setTransform(new Vector2((screenWidth - goalPostThickness) / PPM, panLocation / PPM), 0);
        }

    }

    //Creates animated ball
    public Body createBall(){
        Body bBody;
        BodyDef def = new BodyDef();
        def.type = BodyDef.BodyType.DynamicBody;
        def.position.set(ballX/PPM,ballY/PPM);
        def.fixedRotation = true;
        bBody = world.createBody(def);

        return bBody;
    }

    //Sets radius, density, etc.
    public void setBallProperties(Body body){
        float gbt = screenWidth / 75;  //Goal post thickness
        float ballRadius = (gbt * 1.5f) / PPM;

        // Create a circle shape and set its radius to 6
        CircleShape circle = new CircleShape();

        circle.setRadius(ballRadius);
        // Create a fixture definition to apply our shape to
        FixtureDef fixtureDef = new FixtureDef();
        fixtureDef.shape = circle;
        fixtureDef.density = 3.5f;
        fixtureDef.friction = 0.4f;
        fixtureDef.restitution = 0.6f; // Make it bounce a little bit

        // Create our fixture and attach it to the body
        Fixture fixture = ball.createFixture(fixtureDef);

        circle.dispose();
    }

    public Body createBlock(){
        Body bBody;
        BodyDef def = new BodyDef();
        def.type = BodyDef.BodyType.DynamicBody;
        def.position.set((screenWidth - (goalPostThickness)) / PPM, 0/PPM);
        //def.position.set(-1000, -1000);
        def.fixedRotation = true;
        def.allowSleep = false;
        bBody = world.createBody(def);

        return bBody;
    }


     public void setBlockProperties(Body body){
         PolygonShape square = new PolygonShape();
         square.setAsBox(goalPostThickness/PPM, (goalWidth/2)/PPM);

         // Create a fixture definition to apply our shape to
         FixtureDef fixtureDef = new FixtureDef();
         fixtureDef.shape = square;
         fixtureDef.density = 0.5f;
         fixtureDef.friction = 0.0f;
         fixtureDef.restitution = 0.5f;

         // Create our fixture and attach it to the body
         body.createFixture(fixtureDef);

         square.dispose();
    }

    public static int randInt(int min, int max) {
        Random rand = new Random();
        int randomNum = rand.nextInt((max - min) + 1) + min;
        return randomNum;
    }

    public void attachBlockerShape(Vector2 pos){
        game.shape.setColor(1, 1, 1, 1);
        game.shape.begin(ShapeRenderer.ShapeType.Filled);
        game.shape.rect(pos.x, pos.y, goalPostThickness/PPM, (goalWidth/2)/PPM);
        game.shape.end();
    }
    @Override public void dispose(){
        box2DDebugRenderer.dispose();
        world.dispose();
    }


}
...