how to use defineCollisionRectangle?

266 views Asked by At

For starters, how can I use defineCollisionRectangle API?

I've done some research about it and I think it doesn't have any use at all.

True that I can just use collidesWith() to check if 2 sprites collide.

But what I want to use a sprite that has parameters like house with a backyard fence around it.

I tried using the defineCollisionRectangle() in a condition, set it in the constructor but I don't know how to use it.

I can just use object.getX/gety and object.getWidth/getHeight, to make a Parameter around the sprite.

What does defineCollisionRectangle really do and how do I use it?

1

There are 1 answers

0
gnat On BEST ANSWER

To detect collision for objects like house with a fence around it I would start with defining two Sprite objects - one for fence, another for house - each with its own collision rectangle.

To render a house with fence around it, I'd draw houseSprite over fenceSprite like at the sketch below:

https://i.stack.imgur.com/4Wn5B.jpg

With this approach it would be really easy to tell whether collision happened with fence or with house - simply because each defines its own collision rectangle.


Generally, when you find out that single collision rectangle doesn't do what you need, you invent a way to decompose things to more rectangular sub-elements so that when combined, these elements simulate / approximate desired behavior.

  • End users just don't care how many Sprite objects are there behind the scene. They're happy as long as end result feels about like house with a backyard fence around it.