模拟物理反弹的弹簧阻尼交互

背景

最近交流群在讨论一个酷酷的官网https://labs.lusion.co/,看到里面有一个比较有趣的交互效果,这个鼠标的弹性效果跟IOS的弹性交互有点像,参考这个做了个模拟效果供学习


效果展示

在线Playground: https://stackblitz.com/edit/vitejs-vite-gb3x1qh3?file=src%2Fmain.ts

模拟物理反弹的弹簧阻尼


主要过程

function anim() {
  let velocity = [0, 0];
  let stiffness = 0.04; // 刚度
  let damping = 0.8; // 阻尼

  const dx = targetPosition[0] - currentPosition[0];
  const dy = targetPosition[1] - currentPosition[1];

  velocity[0] += dx * stiffness;
  velocity[1] += dy * stiffness;

  velocity[0] *= damping;
  velocity[1] *= damping;
  const maxSpeed = 200; // 限制最大速度

  // 计算新的速度并限制在最大速度内
  velocity[0] = Math.max(
    Math.min(velocity[0] + dx * stiffness, maxSpeed),
    -maxSpeed
  );
  velocity[1] = Math.max(
    Math.min(velocity[1] + dy * stiffness, maxSpeed),
    -maxSpeed
  );

  velocity[0] *= damping;
  velocity[1] *= damping;

  currentPosition[0] += velocity[0];
  currentPosition[1] += velocity[1];

  setCursorPosition(currentPosition as [number, number]);
  requestAnimationFrame(anim);
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值