繁体   English   中英

在 React.js 中实现重力

[英]Implementing gravity in React.js

我试图在 cookie 图像上实现重力效果。 这个想法是,当它们同时被引力拉动时,它们具有初始加速度和速度。 我使用 setInterval 每 1/60 秒更新 cookies 以达到 60 FPS(这是常见的方法吗?由于在大多数游戏中 FPS 是波动的,我认为它需要以不同的方式完成,但我不知道如何)。 这是我的代码:

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;

我浪费了很多时间来尝试实现正确的物理。 我不确定我现在这样做是否正确。 使用指定的代码,我设法将 y 方向的速度增加 1,将 x 方向的 position 每秒增加 10。 所以我认为它对吗? 将不胜感激任何帮助。 如果 cookies 不仅水平加速,这是否也有效?

Physics.js 看起来像这样:

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);
}

希望有人可以帮助我,可以批准它做得对,或者给我提示如何做得更好!

由于 JavaScript 是单线程并使用事件循环,因此无法保证定时器延迟。 相反,您应该使用增量计时方法:

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);
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM