Skip to content

Commit

Permalink
fix pets flickering and the pet randomly disappear.
Browse files Browse the repository at this point in the history
  • Loading branch information
SeakMengs committed Aug 16, 2023
1 parent e69c375 commit 9a9c615
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 50 deletions.
92 changes: 43 additions & 49 deletions src/Canvas.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,68 +9,62 @@ function Canvas() {
const currentScreenHeight: number = Math.round(DPR * window.screen.height);
const canvasRef = useRef<HTMLCanvasElement>(null);
const FPS = 60;
const { pets, addPet, clearPets, isPetsInitialized, setIsPetsInitialized } = usePetStore((state) => ({
pets: state.pets,
addPet: state.addPet,
clearPets: state.clearPets,
isPetsInitialized: state.isPetsInitialized,
setIsPetsInitialized: state.setIsPetsInitialized
}));
const Interval = 1000 / FPS;
const requestAnimateFrameId = useRef<number>(0);
const { pets, clonePets, isPetsInitialized, setIsPetsInitialized } = usePetStore();

// disable right click (context menu) for build version only. uncomment for development
// credit: https://github.com/tauri-apps/wry/issues/30
document.addEventListener('contextmenu', event => event.preventDefault());

//* credit: https://medium.com/@pdx.lucasm/canvas-with-react-js-32e133c05258
useEffect(() => {
getAppSettings({ path: "pets.json" }).then((petConfig) => {
const petConf = JSON.parse(JSON.stringify(petConfig));

// prevent pets initialize more than once when pets.json is updated
if (petConf.length < pets.length) return () => {
clearPets();
setIsPetsInitialized(false);
}

if (petConf.length > 0 && !isPetsInitialized) {
for (let i = 0; i < petConf.length; i++) {
addPet(new Pet(petConf[i]));
}
setIsPetsInitialized(true);
// console.log("pets initialized");
(async () => {
const petConfig = await getAppSettings({ path: "pets.json" });
const tempPets: Pet[] = [];
for (let i = 0; i < petConfig.length; i++) {
tempPets.push(new Pet(petConfig[i]));
}
clonePets(tempPets);
})();
}, [isPetsInitialized]);

if (pets.length === 0 && isPetsInitialized) return;
useEffect(() => {
let timeoutId: any;
const canvas = canvasRef.current;
const context = canvas?.getContext("2d");
canvas!.width = window.innerWidth;;
canvas!.height = currentScreenHeight;

// console.log(pets);
const canvas = canvasRef.current;
const context = canvas?.getContext("2d");
canvas!.width = window.innerWidth;;
canvas!.height = currentScreenHeight;
function animate() {
context!.save();
context!.imageSmoothingEnabled = false;

function animate() {
context!.save();
context!.imageSmoothingEnabled = false;
// credit: https://stackoverflow.com/questions/4815166/how-do-i-make-a-transparent-canvas-in-html5
context!.clearRect(0, 0, canvas!.width, canvas!.height);
// credit: https://stackoverflow.com/questions/4815166/how-do-i-make-a-transparent-canvas-in-html5
context!.clearRect(0, 0, canvas!.width, canvas!.height);

// Debug purposes
// context.fillStyle = 'black'
// context.fillRect(0, 0, canvas.width, canvas.height)
// Debug purposes
// context.fillStyle = 'black'
// context.fillRect(0, 0, canvas.width, canvas.height)

if (pets.length > 0) {
for (let i = 0; i < pets.length; i++) {
pets[i].animateBehavior();
pets[i].update(context as CanvasRenderingContext2D);
}
if (pets.length > 0) {
for (let i = 0; i < pets.length; i++) {
pets[i].animateBehavior();
pets[i].update(context as CanvasRenderingContext2D);
}

context!.restore();
setTimeout(() => {
window.requestAnimationFrame(animate)
}, 1000 / FPS);
}
animate();
});

context!.restore();
timeoutId = setTimeout(() => {
requestAnimateFrameId.current = window.requestAnimationFrame(animate);
}, Interval);
}
requestAnimateFrameId.current = window.requestAnimationFrame(animate);

return () => {
clearTimeout(timeoutId);
window.cancelAnimationFrame(requestAnimateFrameId.current);
setIsPetsInitialized(false);
}
}, [pets]);

return (
Expand Down
5 changes: 4 additions & 1 deletion src/hooks/usePetStore.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import { create } from "zustand";
import { CurrentPetState, States } from "../Class/type";


export type TPet = {
position: { x: number; y: number };
name: string;
Expand Down Expand Up @@ -32,6 +31,7 @@ export type TPet = {

interface PetStore {
pets: TPet[];
clonePets: (pets: TPet[]) => void;
addPet: (pet: TPet) => void;
clearPets: () => void;
isPetsInitialized: boolean;
Expand All @@ -40,6 +40,9 @@ interface PetStore {

export const usePetStore = create<PetStore>()((set) => ({
pets: [],
clonePets: (pets: TPet[]) => {
set({ pets: [...pets] });
},
addPet: (pet: TPet) => {
set((state) => ({ pets: [...state.pets, pet] }));
},
Expand Down

0 comments on commit 9a9c615

Please sign in to comment.