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.