将Processing Java代码转P5.js遇构造器重载及自引用问题求助
Java Processing转P5.js:构造器重载与实例数组处理方案
问题a:构造器重载的替代实现
JS/TS不支持Java式的构造器重载,我们可以在单个构造函数里通过判断参数类型来实现不同逻辑:
- 若传入两个数字,执行原第一个构造函数的初始化逻辑
- 若传入Finder实例,执行原拷贝构造函数的逻辑
问题b:自引用实例的数组添加操作
原Java代码用append()方法扩展数组,P5.js中直接用数组的push()方法即可。注意要提前初始化全局的paths数组,避免未定义错误。
完整转换后的P5.js代码(JS版本)
let paths = []; // 提前初始化全局数组 class Finder { constructor(xOrParent, y) { this.origin = createVector(width / 2, height / 2); // P5.js用createVector替代new PVector // 判断参数类型,实现重载逻辑 if (typeof xOrParent === 'number' && typeof y === 'number') { this.location = createVector(width / 2, height / 2); this.velocity = createVector(xOrParent, y); this.diameter = 8; } else if (xOrParent instanceof Finder) { const parent = xOrParent; this.location = parent.location.copy(); // P5.js中p5.Vector的copy()对应Java的get() this.velocity = parent.velocity.copy(); const area = PI * sq(parent.diameter / 2); const newDiam = sqrt(area / 2 / PI) * 2; this.diameter = newDiam; parent.diameter = newDiam; } } update() { if (this.origin.dist(this.location) > 300) { // 空逻辑保持不变 } else if (this.diameter > 0.5) { this.location.add(this.velocity); const bump = createVector(random(-1, 1), random(-1, 1)); bump.mult(0.1); this.velocity.add(bump); this.velocity.normalize(); if (random(0, 1) < 0.02) { // 用push()替代Java的append() paths.push(new Finder(this)); } } } } // 示例初始化(可在setup中调用) function setup() { createCanvas(600, 600); paths.push(new Finder(1, 0)); // 初始化第一个Finder实例 } function draw() { background(255); paths.forEach(finder => { finder.update(); // 可添加绘制逻辑,比如ellipse(finder.location.x, finder.location.y, finder.diameter) }); }
关键改动说明
- 构造器重载替代:通过
typeof和instanceof判断参数类型,在单个构造函数内分支处理不同初始化逻辑 - PVector替换:P5.js中使用
createVector()创建向量,copy()方法替代Java Processing的get()实现向量克隆 - 数组操作:用JS原生数组的
push()方法替代Processing Java的append(),无需类型转换 - 全局数组初始化:提前声明并初始化
paths数组,避免运行时未定义错误
内容的提问来源于stack exchange,提问作者Daniel
相关产品推荐
相关产品推荐

