Understanding playdate.geometry.rect:intersection()

,

I'm using the current Mac SDK with Lua.

I'm wanting to use the rect:intersection method in the lua api to do exactly what it states its use case as. I have a sprite and I want to use the intersection of it and another sprite as a new rect that represents that intersection. The problem is, the result I get back is just a rect with the exact same width and height as the first rect regardless of how much intersection there is.

To debug this, I tested the rect:intersection method in an isolated case:

testSprite1 = gfx.sprite.new()
testSprite2 = gfx.sprite.new()

colRect1 = testSprite1:setCollideRect(0,0,20,20)
colRect2 = testSprite2:setCollideRect(0,0,20,20)

testSprite1:moveTo(130,200)
testSprite2:moveTo(120,200)

testSprite1:add()
testSprite2:add()

print("test collision overlap: ", testSprite1:getCollideRect():intersection(testSprite2:getCollideRect()))

The result I get above is "test collision overlap: (0,0,20,20)" where I would expect to get a rect of (0,0,10,20). If I change the overlap of the sprites, I get the same result.

Am I misunderstanding how to use this method?

Thanks!

Hello, the reason you are seeing this result is because the getCollideRect function will return exactly what you set with setCollideRect, since both colliders (rectangles) are the same size, the result is 0, 0, 20, 20. When you call setCollideRect, the first two arguments are x and y, but they are relative to the sprite size, not the sprite position (set with moveTo, moveBy).

To achieve the result you want, you can use the sprite size directly with getBoundsRect. The example would look something like this:

import "CoreLibs/sprites"

local pd_graphics <const> = playdate.graphics

local testSprite1 <const> = pd_graphics.sprite.new()
testSprite1:moveTo(130, 200)
testSprite1:setSize(20, 20)

local testSprite2 <const> = pd_graphics.sprite.new()
testSprite2:moveTo(120, 200)
testSprite2:setSize(20, 20)

testSprite1:add()
testSprite2:add()

print("test collision overlap: ", testSprite1:getBoundsRect():intersection(testSprite2:getBoundsRect()))

EDIT: If collisions are what you are after, the easiest way to detect sprite collisions is with the integrated collision system (moveWithCollision, overlappingSprites etc.). If you want to implement your own collision system, for example through the geometry rects and still use sprites, then you can use something like this:

playdate.geometry.rect.fast_intersection(sprite1.x, sprite1.y, sprite1.width, sprite1.height, sprite2.x, sprite2.y, sprite2.width, sprite2.height)

Thanks! I would normally just use the collision system but I need to know exactly how much overlap there is before I decide to do anything with the collision. I think your fast_intersection reference is exactly what I need.

Thanks again!