Hi,
I am using Java, Libgdx, box2d

I main class I have created a body and I set player x and y position to 50.

// main class
public class main{
  ...
  private void createPlayer() {
    BodyDef bdef = new BodyDef();
    Body body;
    FixtureDef fdef = new FixtureDef();
    PolygonShape shape = new PolygonShape();

    /*** Body - Player ***/
    bdef.type = BodyType.DynamicBody;
    bdef.position.set(50 / PPM, 50 / PPM);
    bdef.linearVelocity.set(1.5f, 0);
    body = world.createBody(bdef);
        .....
  }
}

How can I set player x and y position to 100.

//player class
public class player{
       public player(Body body){
             super(body);
       }

       ....
       public void update(){
             //get player x position
             currentX = this.getBody().getPosition().x;

             //how to change player x and y position to 100?   
       }
}

Recommended Answers

All 3 Replies

update takes an object of type BodyDef. Then you can set it using the setters just as in the object bdef

here is what i tried. but didnt worked bc CreatePlayer() method is in Main class constructor.

// main class

public class main{
  ...
  public main(){
      createPlayer();
  }

  private void createPlayer() {
    BodyDef bdef = new BodyDef();
    Body body;
    FixtureDef fdef = new FixtureDef();
    PolygonShape shape = new PolygonShape();

    /*** Body - Player ***/
    bdef.type = BodyType.DynamicBody;
    bdef.position.set(50 / PPM, 50 / PPM);
    bdef.linearVelocity.set(1.5f, 0);
    body = world.createBody(bdef);
        .....
    player = new Player(bdef);
  }

  ....

  public void update(float dt) {
      playerObj.update(dt);
      ...
  }
}

//player class

public class player{
       public player(Body body, BodyDef bdef){
             super(body);
             this.bdef = bdef;
       }

       ....
       public void update(){
             //get player x position
             currentX = this.getBody().getPosition().x;

             //how to change player x and y position to 100? 
             bdef.position.set(100, 100);
       }
}

Huh? You passed in only 1 argument in creating new Player object but require 2 arguments in the Player constructor class?

After looking Body API doc, there is a method called setTransform(Vector2, float) which should allow you to set the position but it takes the angle of rotation as well. Maybe that's the one you should use?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.