0

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?   
       }
}
3
Contributors
3
Replies
37
Views
3 Years
Discussion Span
Last Post by Taywin
0

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

0

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

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?

Edited by Taywin

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.