Search code examples
javalibgdxpositionbounding-box

How to set BoundingRectangle Position


I tried to set the bounding rectangle position.

spr.getBoundingRectangle().setPosition(100,100);
Sytem.out.println(spr.getBoundingRectangle.getX() + " " + spr.getBoundingRectangle.getX());
// and the output is always 0,0(position)

I also tried to set it's position whenever condition == true

if(justTouched == true){
     spr.getBoundingRectangle().setPosition(100,100);
    Sytem.out.println(spr.getBoundingRectangle.getX() + " " + spr.getBoundingRectangle.getX());
}// but the result is the same

Solution

  • The bounding Rectangle is generated and/or updated when you call getBoundingRectangle(). This means that you aren't modifying the sprite vertices by using setX or setY of the Rectangle class. Instead use Sprite.setPosition(x,y); Moving the sprite this way moves the bounding rectangle.

    There are also the following methods that alter the bounding rectangle of a sprite (don't confuse this setX and setY with the Rectangle classes setX and setY, this one modifies the sprite's vertices):

    setX(x)
    setY(y)
    setBounds(x,y,width,height)
    setSize(width,height)
    translate(diffX,diffY)
    translateX(diffX)
    translateY(diffY)
    

    The way that seems to fit your question best would be the following.

    spr.setPosition(100,100);
    Rectangle sprBounds = spr.getBoundingRectangle();
    Sytem.out.println(sprBounds.getX() + " " + sprBounds.getY());