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

p5.js OOP编程中如何点击鼠标修改物体速度并解决画布无显示问题

问题原因&修改点

  • 核心语法错误:你把mouseIsPressed的判断逻辑直接写在了Ball类的方法外部,属于类定义的非法语法,直接导致整个代码运行失败,所以画布无内容。这部分逻辑要放到类的方法内(比如move方法里,或者单独写一个响应点击的方法)
  • 类属性缺失:xdirection、ydirection你定义成了全局变量,但bounce和move方法里都是通过this.xdirection调用,类实例没有这两个属性,移动和碰撞逻辑都会失效,需要把这两个属性放到类的constructor里初始化
  • 位置被重复重置:draw函数里每次渲染都强制给ball1的x、y赋值为固定值,就算移动逻辑正常,小球也会被固定在同一个位置无法移动,删掉这两行赋值即可
  • 碰撞检测参数不匹配:全局rad值设为50,但你定义的小球宽高只有30,实际半径是15,碰撞判断的边界会出现偏移,建议把半径作为类属性管理
  • 冗余方法调用:鼠标点击逻辑里的this.fill()是无效写法,fill是p5提供的全局函数,不需要加this调用

修正后运行代码,初始小球静止在画布顶部,按住鼠标时小球会开始移动,碰到画布边界会自动反弹,完整代码如下:

let ball1;

function setup() {
  createCanvas(400, 400);
  ball1 = new Ball();
}

function draw() {
  background(220);
  ball1.body();
  ball1.move();
  ball1.bounce();
}

class Ball {
  constructor(){
    this.x = width/2;
    this.y = 50;
    this.w = 30;
    this.h = 30;
    this.rad = this.w / 2;
    this.c = color(25,0,100);
    this.xspeed = 0;
    this.yspeed = 0;
    this.xdirection = 1;
    this.ydirection = 1;
  }
  
  body(){
    noStroke();
    fill(this.c);
    ellipse(this.x, this.y, this.w, this.h);
  }

  move() {
    if(mouseIsPressed) {
      this.xspeed = 1.5;
      this.yspeed = 1.5;
    }
    this.x = this.x + this.xspeed * this.xdirection;
    this.y = this.y + this.yspeed * this.ydirection;
  }
  
  bounce() {
    if (this.x > width - this.rad || this.x < this.rad) {
      this.xdirection *= -1;
    }
    if (this.y > height - this.rad || this.y < this.rad) {
      this.ydirection *= -1;
    }
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 21:36:02