*Collision Detection Question*: I am dragging some...
# compose
n
Collision Detection Question: I am dragging some boxes around my screen and I want to create an animation when one box touches another. Is this possible or would I be better off transferring everything to a Canvas? If it is possible, could someone please point me in the right direction. I can deal with the doc; I just don't know where to start to detect collision between boxes in Compose. Thanks!
👀 1
o
There is no builtin functionality for this, afaik. You need to do it yourself (for rectangles it’s easy), or use some 2d lubrary for advanced features
n
Thanks for the reply. When you say it's easy, could you give me a clue so I can get started. Also, do you have a library to recommend? Or just an example library? Many thanks!
o
Well, test for rectangle collisions is just comparing for intersection, right? It’s just a couple of comparisons of edges. Draw it on a piece of paper and you’ll figure it out :) I’m on mobile now, so can’t assist you further. As for libs, box2d could work, or may be look for something smaller/easier
n
Brilliant thanks so much, it'll get me started! 😊
s
So the simplest way would be to loop over all the boxes (except the one you're dragging) and check for collision one by one. For rectangles: https://stackoverflow.com/questions/31022269/collision-detection-between-two-rectangles-in-java
👍 1
n
Hi yes, I actually have done this before using a canvas. My question was more in relation to the fact that I am using boxes, and that I don't know if it's possible to get the bounds of a box (I mean the Box composable)...
o
You can get bounds with onGlobalPosition event (don’t remember exact name)
n
ah ok perfect!
s
Yeah you can use either
onGlobalPosition
or keep a list of bounds and draw your boxes based on them and update your bounds in your
onDrag
or whatever you have for dragging. I'm doing something like this:
Copy code
val boxes = remember { mutableStateListOf<MyBoxClass>(...) } // Initialize the default bounds here

Box(modifier = Modifier.fillMaxSize()) {
    boxes.forEach { box ->
        Box(modifier = Modifier
                .offset(box.x, box.y)
                .pointerInput(Unit) {
                    // update bounds here
                }
                .size(box.width, box.height))
    }
}
n
Thanks both, I'll try all that tonight!