I have a body and a sprite which I want to link to that body.
My first idea was to set Sprite position to body position like this:
//(Inside my sprite's update method)
Vector2 bodyPos = new Vector2(body.getPosition().x - ship.getDimensions().x / 2, body.getPosition().y - ship.getDimensions().y / 2);
ship.setPosition(bodyPos);
ship.setRotation((float) Math.toRadians(body.getAngle()));
Because I am just drawing one or two bodies and sprites to see how things work, so far there are no problems with that method.
But then I accidentally found out about body.setUserData(Object) method. Wondering if this has any advantages or deals with something I have not encountered or thought about, I went to libgdx documentation and found this (at https://code.google.com/p/libgdx/wiki/PhysicsBox2D):
Iterator<Body> bi = world.getBodies();
while (bi.hasNext()){
Body b = bi.next();
// Get the bodies user data - in this example, our user
// data is an instance of the Entity class
Entity e = (Entity) b.getUserData();
if (e != null) {
// Update the entities/sprites position and angle
e.setPosition(b.getPosition().x, b.getPosition().y);
// We need to convert our angle from radians to degrees
e.setRotation(MathUtils.radiansToDegrees * b.getAngle());
}
}
So if I have only one body and not an array of bodies and sprites, it will be like this:
body.setUserData(mySprite);
(when rendering)
(Sprite)body.getUserData().setPosition(values);
Right? Because I don’t have many bodies and certainly I don’t need an iterator.
So, is this method only useful with many bodies? Or is it my method wrong or inefficient?
The other question is, I have my sprite in one class and body in another class (Actually I have a static method which creates a body wherever I want etc). These two do not know about each other. That is to say, no references, no parameters about each other.
Should I write them like this:
//Sprite constructor
public MySprite(parameters, no body parameters){
}
//Body constructor
public MyBody(other parameters, Object userData){
//other code
body.setUserData(userData);
}
I hope you can enlighten me with your ideas and knowledge
EDIT: Dammit, I just realized there is a MathUtils class