Intersection Observer Not Detecting Collisions in React Breakout Game with TypeScript

I’m working on a Breakout game in React using TypeScript. The game is divided into three main components: WallGrid, Ball, and PlayerSlider. These components are connected using a Game component. I’m using the Intersection Observer API to detect collisions between the ball and the bricks, as well as the ball and the player’s paddle.

Here is the code for the WallGrid, Ball, and PlayerSlider components:

WallGrid.tsx:

typescript
import React, { useEffect, useRef } from "react";
import style from "./style.module.css";

interface Props {
    wallMatrix: number[][];
    observer: IntersectionObserver;
    brickRefs: React.RefObject<React.RefObject<HTMLDivElement>[]>;
}

const WallGrid = ({ brickRefs, observer, wallMatrix }: Props) => {
  useEffect(() => {
    if (brickRefs.current) {
      const refs = wallMatrix.flat().map(() => React.createRef<HTMLDivElement>());
      brickRefs.current.length = 0;
      brickRefs.current.push(...refs);
    }
  }, [wallMatrix]);

  useEffect(() => {
    if (observer && brickRefs.current) {
      brickRefs.current.forEach((ref) => {
        if (ref.current) observer.observe(ref.current);
      });
    }

    return () => {
      if (observer && brickRefs.current) {
        brickRefs.current.forEach((ref) => {
          if (ref.current) observer.unobserve(ref.current);
        });
      }
    };
  }, [brickRefs.current, observer]);

  return (
    <div className="w-full gap-1 h-1/2 grid grid-rows-8 grid-cols-12">
      {wallMatrix.map((matrix, index1) =>
        matrix.map((item, index2) => {
          if (item > 0) {
            const refIndex = index1 * wallMatrix[0].length + index2;
            return (
              <span
                ref={brickRefs.current && brickRefs.current[refIndex]}
                key={`${index1}-${index2}`}
                className={"border-2 border-black rounded-2xl " + style[`brick-${item}`]}
                style={{
                  gridRowStart: index1 + 1,
                  gridRowEnd: index1 + 2,
                  gridColumnStart: index2 + 1,
                  gridColumnEnd: index2 + 2
                }}
              ></span>
            );
          }
          return null;
        })
      )}
    </div>
  );
};

export default WallGrid;

Ball.tsx:

typescript

import React, { useState, useEffect, useRef } from 'react';

interface Props {
    ballRef: React.RefObject<HTMLDivElement>;
    setObserver: React.Dispatch<React.SetStateAction<IntersectionObserver | null>>;
}

const Ball = ({ setObserver, ballRef }: Props) => {
    const [position, setPosition] = useState({ x: 50, y: 100 });
    const [velocity, setVelocity] = useState({ dx: 1, dy: 1 });
    const positionRef = useRef(position);
    const velocityRef = useRef(velocity);

    useEffect(() => {
        positionRef.current = position;
    }, [position]);

    useEffect(() => {
        velocityRef.current = velocity;
    }, [velocity]);

    const changeDirection = (xAxis = false, yAxis = false) => {
        setVelocity((prev) => {
            const newVelocity = {
                dx: xAxis ? -prev.dx : prev.dx,
                dy: yAxis ? -prev.dy : prev.dy
            };
            velocityRef.current = newVelocity;
            return newVelocity;
        });
    };

    const updatePosition = () => {
        setPosition((prev) => {
            const newPosition = {
                x: prev.x + velocityRef.current.dx,
                y: prev.y + velocityRef.current.dy
            };
            positionRef.current = newPosition;
            return newPosition;
        });
    };

    useEffect(() => {
        const moveBall = () => {
            updatePosition();
            const { x, y } = positionRef.current;

            if (x <= 0 || x >= window.innerWidth - 40) changeDirection(true, false);
            if (y <= 90 || y >= window.innerHeight - 40) changeDirection(false, true);

            requestAnimationFrame(moveBall);
        };

        const animationFrameId = requestAnimationFrame(moveBall);
        return () => cancelAnimationFrame(animationFrameId);
    }, []);

    return (
        <div
            ref={ballRef}
            className='border-2 border-black bg-red-600 w-10 h-10 rounded-full'
            style={{
                position: 'absolute',
                left: `${position.x}px`,
                top: `${position.y}px`,
            }}
        ></div>
    );
};

export default Ball;

PlayerSlider.tsx:

typescript

import { useEffect } from 'react';
import useTransformX from '../../hooks/useTransformX';

const PlayerSlider = ({ observer, playerRef }: { observer: IntersectionObserver; playerRef: React.RefObject<HTMLDivElement> }) => {
    const transform = useTransformX();

    useEffect(() => {
        if (playerRef.current && observer) {
            console.log('Player observer initialized');
            observer.observe(playerRef.current);
        }

        return () => {
            if (playerRef.current && observer) {
                console.log('unobserving');
                observer.unobserve(playerRef.current);
            }
        };
    }, [playerRef.current, observer]);

    return (
        <div
            ref={playerRef}
            style={{
                transform: `translateX(${transform}px)`
            }}
            className={`w-56 h-10 bg-red-600 border-2 border-black rounded-3xl`}
        ></div>
    );
};

export default PlayerSlider;

All these components are connected using the Game component:

Game.tsx:

typescript

import { matrices } from "./../utils/getWallMetrix";
import WallGrid from '../components/WallGrid';
import { useParams } from 'react-router-dom';
import PlayerSlider from "../components/PlayerSlider";
import Ball from "../components/Ball";
import { useEffect, useRef, useState } from "react";

const Game = () => {
  let { id = 0 } = useParams();   
  
  const [observer, setObserver] = useState<IntersectionObserver | null>(null);
  const ballRef = useRef<HTMLDivElement>(null);
  const playerRef = useRef<HTMLDivElement>(null);
  const brickRefs = useRef<React.RefObject<HTMLDivElement>[]>([]);

  useEffect(() => {
    if (ballRef.current) {
        setObserver(new IntersectionObserver((entries) => {
            entries.forEach((entry) => {
                if (entry.isIntersecting) {
                    console.log('Collision detected with:', entry.target);
                    // Handle collision
                }
            });
        }, {
            root: null,
            rootMargin: "0px",
            threshold: 0.1
        }));
    }
  }, [ballRef.current]);

  return (
    <>
      <div className="h-[10vh] relative flex gap-10">
        <p>High Score: 0</p>
        <p>Score: 0</p>
        <p>Time: 00:00</p>
      </div>
      <div className='w-screen bg-[#2f3542] border-4 border-red-600 flex py-1 flex-col justify-between h-[90vh] '>
        <WallGrid brickRefs={brickRefs} observer={observer} wallMatrix={matrices[+id]} />
        <Ball ballRef={ballRef} setObserver={setObserver} />
        <PlayerSlider playerRef={playerRef} observer={observer} />
      </div>
    </>
  );
}

export default Game;
The game initializes fine, but I encounter issues with the observer pattern. Specifically, the ball seems to intermittently stop detecting collisions with the bricks and the player paddle. I'm not sure if I'm handling the refs or the observer correctly.

Here are my main questions:

Am I correctly setting up the Intersection Observer for the bricks and the player paddle?
    
Are there any improvements or corrections needed in my use of refs to ensure reliable collision detection?

Any help or suggestions would be greatly appreciated!

New contributor

bharat gawar is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật