0

I'm wondering, in React, if there is some way we can listen for 2 components or objects touching / crossing? Has anyone experienced this and how did you resolve the issue?

I found one way, however it doesn't detect moving objects for some reason, in this case ".log" moves on the X axis, if ".player" touches, the program doesn't detect the touch.

Is there any package that solves this problem?

const Test = () => {
    const [player, setPlayer] = useState({
        x: 0,
        y: 0,
    });

    useEffect(() => {
        const handleKeyDown = (e) => {
            if (e.keyCode === 87 || e.key === 'ArrowUp') {
                setPlayer((prev) => ({
                    ...prev,
                    y: prev.y + 50,
                }));
            }
            if (e.keyCode === 83 || e.key === 'ArrowDown') {
                setPlayer((prev) => ({
                    ...prev,
                    y: prev.y - 50,
                }));
            }
        };

        window.addEventListener('keydown', handleKeyDown);
        return () => {
            window.removeEventListener('keydown', handleKeyDown);
        }
    }, [player])

    useEffect(() => {
        const div = document.querySelector('.log');
        const player = document.querySelector('.player');

        const divRect = div.getBoundingClientRect();
        const playerRect = player.getBoundingClientRect();

        if (
            playerRect.top < divRect.bottom &&
            playerRect.bottom > divRect.top &&
            playerRect.left < divRect.right &&
            playerRect.right > divRect.left
        ) {
            console.log('touched');
        }
    }, [player])

    return (
        <>
            <div
                className='player-container'
                style={{ left: player.x, bottom: player.y }}
            >
                <div className='player' />
            </div>
            <div
                className='log'
                style={{
                    position: 'absolute',
                    width: '50px',
                    height: '50px',
                    background: 'red',
                }}
            ></div>
        </>
    )
}
  • 1
    The problem has nothing to do with React, check [JavaScript: Collision detection](https://stackoverflow.com/q/2440377/387194) – jcubic Jun 28 '23 at 09:55

0 Answers0