You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用class创建弹跳球时出现故障:球体卡顿在页面底部求助

弹跳球卡顿在页面底部的问题修复

问题根源分析

  1. 速度被重复重置
    每次draw()调用bounce(5,5)时,都会强制把xSpeed和ySpeed设为5,覆盖了反弹后的反向速度,导致球体无法保持正确的运动方向。

  2. 条件判断嵌套错误
    检测y轴边界的if语句被包裹在x轴边界的if块内,只有当球体碰到左右边界时,才会检查上下边界,大部分时候y轴碰撞完全不生效,球体直接掉到底部后无法反弹。

  3. 边界判断未考虑球体半径
    以球心位置判断边界,会导致球体一半超出画布后才触发反弹,视觉上球体卡出画布,正确的判断应该基于球体边缘与画布边界的接触。

修正后的代码

class Particle {
  constructor(x, y, r) {
    this.x = x;
    this.y = y;
    this.r = r;
    // 将初始速度放在构造函数中,避免每次重置
    this.xSpeed = 5;
    this.ySpeed = 5;
  }
  
  bounce() {
    // 修正条件判断的嵌套问题,分开判断x和y的边界
    if (this.x - this.r < 0 || this.x + this.r > width) {
      this.xSpeed *= -1;
    }
    
    if (this.y - this.r < 0 || this.y + this.r > height) {
      this.ySpeed *= -1;
    }

    this.x += this.xSpeed;
    this.y += this.ySpeed;
  }
  
  display() {
    fill(0, 255, 0);
    stroke(0);
    strokeWeight(1);
    circle(this.x, this.y, this.r);
  }
}

let balloon;
function setup(){
  createCanvas(windowWidth, windowHeight);
  balloon = new Particle(100, 100, 100);
}

function draw(){
  background(245);
  
  balloon.bounce(); // 不再传递速度参数
  balloon.display();
}

关键修改点

  • 将速度初始化移到constructor中,bounce方法不再接收速度参数,避免每次调用重置速度。
  • 拆分嵌套的if语句,分别独立判断x轴和y轴的边界碰撞。
  • 边界判断加入球体半径计算,确保球体边缘碰到画布边界时就触发反弹。

内容的提问来源于stack exchange,提问作者Jiji

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.25 22:48:40