Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

114
Visualizações
Implementing gravity in React.js

Im trying to implement a gravity effect on cookie images. The idea was that they have an initial acceleration and velocity while they are being pulled by the gravitational force at the same time. I used setInterval to update the cookies every 1/60th second to achieve 60 FPS (Is this the common approach? Since in most games FPS is fluctuating i assume that it needs to be done differently, but i don't know how). Here is my code:

import './App.css';
import cookie from '../src/images/cookie.png';
import { Vector } from './Physics';
import { useEffect, useState } from 'react';

const GRAVITY = 1;

function App() {
  const initCookieProps = () => {
    let cookiesProps = [];
    for(let i = 0; i < 1; i++){
      let cookieProps = {};
      cookieProps['pos'] = new Vector(0,0);
      cookieProps['acceleration'] = new Vector(0, GRAVITY);
      cookieProps['velocity'] = new Vector(10, 0);
      cookiesProps.push(cookieProps);
    }
    return cookiesProps;
  }

  const [cookiesProps, setCookiesProps] = useState(() => {
    const initialState = initCookieProps();
    return initialState;
  })

  const updateCookies = (delta) => {
    setCookiesProps(cookiesProps.map(cookieProps => {
      cookieProps['velocity'] = cookieProps['velocity'].add(cookieProps['acceleration'].multiply(delta));
      cookieProps['pos'] = cookieProps['pos'].add(cookieProps['velocity'].multiply(delta));
      return cookieProps;
    }));
  }

  useEffect(() => {
    setInterval(() => {
      updateCookies(1/60);
    }, 1000/60);
  }, [])
  
  return (
    <div className="content">
      {cookiesProps.map( props => <img className="cookie" style={{left: props['pos'].x, top: props['pos'].y}} src={cookie} alt="cookie"/>)}
    </div>
  );
}

export default App;

I wasted a lot of hours trying to implement the correct Physics. I'm not sure if it is correct the way i am doing it right now. With the specified code i managed to increase the velocity in the y-direction by 1, and the position in x direction by 10 every second. So i think its right? Would appreciate any help. Would this also work if the cookies are not only accelerated horizontally?

Physics.js looks like this:

export function Vector(x,y){
    this.x = x;
    this.y = y;
}

Vector.prototype.normalize = function() {
    const abs = Math.sqrt(this.x*this.x+this.y*this.y);
    return new Vector(this.x/abs, this.y/abs);
}

Vector.prototype.add = function(other) {
    return new Vector(this.x+other.x,this.y+other.y);
}

Vector.prototype.multiply = function(scalar){
    return new Vector(this.x*scalar,this.y*scalar);
}

Vector.prototype.subtract = function (other){
    return new Vector(this.x-other.x,this.y-other.y);
}

Hope someone can help me, can approve that it is done right, or maybe give me tips how to do it better!

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

As JavaScript is single-threaded and uses an event loop, timer delay is not guaranteed. Instead you should use a delta timing approach:

class DeltaTimer {
    constructor(func, delay) {
        this.func = func;
        this.delay = delay;
    }

    start() {
        this.lastTime = Date.now();
        this.timeout = setTimeout(this.loop.bind(this), this.delay);
    }

    stop() {
        if (this.timeout) {
            clearTimeout(this.timeout);
        }
    }

    loop() {
        const now = Date.now();
        const delta = now - lastTime;
        this.func(delta);

        this.lastTime = now;
        this.timeout = setTimeout(this.loop.bind(this), this.delay);
    }
}
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda