Cuddl3s
Cuddl3s

Reputation: 163

How to get a region of rotated Actor in libgdx

In a small game I am developing using libgdx, I have spears as game objects. I implemented them using Scene2D, as a subclass of Actor. The spears can be rotated by multitudes of 90° . I want to have just the "speartip" part of my image as a part that "hurts" the Player, the shaft shall be harmless. So when I construct my Spear object, I also construct 2 rectangles that cover the tip and the shaft of the spear. But when my actor gets rotated using setRotation() , the rectangles obviously don't, cause they aren't "attached" to the spear object.

Do you have some suggestions on how to handle this kind of stuff? Code below.

    public TrapEntity(Texture texture, float pos_x, float pos_y, float width, float height, Vector2 center,
                  float rotation, Rectangle hurtZone, Rectangle specialZone) {
    super(texture, pos_x, pos_y, width, height, center, rotation);

    this.hurtZone = new Rectangle(hurtZone.getX(), hurtZone.getY(), hurtZone.getWidth(), hurtZone.getHeight());
    this.specialZone = new Rectangle(specialZone.getX(), specialZone.getY(), specialZone.getWidth(), specialZone.getHeight());

}

And the render method in the same class. I use it to render the bounds of the "hurtZone" rectangle:

    @Override
public void draw(Batch batch, float alpha){
    super.draw(batch, alpha);
    batch.end();
    sr.setProjectionMatrix(batch.getProjectionMatrix());
    sr.setTransformMatrix(batch.getTransformMatrix());
    sr.begin(ShapeRenderer.ShapeType.Line);
    sr.setColor(Color.RED);
    sr.rect(hurtZone.getX(), hurtZone.getY(), hurtZone.getWidth(), hurtZone.getHeight());
    sr.end();
    batch.begin();

}

Upvotes: 0

Views: 213

Answers (1)

hamham
hamham

Reputation: 571

Rectangles can't be rotated, I had to do a similar thing and struggled with finding a solution. The best solution I have found yet is to use a Polygon. You would do something like this;

    //Polygon for a rect is set by vertices in this order
    Polygon polygon = new Polygon(new float[]{0, 0, width, 0, width, height, 0, height});

    //properties to update each frame
    polygon.setPosition(item.getX(), item.getY());
    polygon.setOrigin(item.getOriginX(), item.getOriginY());
    polygon.setRotation(item.getRotation());

Then, to check if a point is within the rotated Polygon use;

    polygon.contains(x, y);

Upvotes: 1

Related Questions