如何让Java Processing中每条线段的向量点移向屏幕中心?
实现点击点向中心移动的解决方案
核心思路
要让端点向中心移动,关键是在draw()循环里持续更新每个点击点的坐标,逐步向(300,300)靠近。可以用Processing内置的lerp()函数实现平滑趋近,或者直接通过坐标差值计算移动量。
修改后的完整代码
float[] Xcont = new float[0]; float[] Ycont = new float[0]; int clickCounter = 0; float centerX = 300; float centerY = 300; // 控制移动速度,值越小移动越慢越平滑 float moveSpeed = 0.01f; void setup(){ size(600, 600); background(0); } void draw(){ background(0); // 每次重绘清空画布,避免残留轨迹 stroke(255); if(clickCounter == 20){ // 先更新所有点的坐标,向中心移动 for(int i = 0; i < Xcont.length; i++){ // 用lerp实现平滑向中心趋近 Xcont[i] = lerp(Xcont[i], centerX, moveSpeed); Ycont[i] = lerp(Ycont[i], centerY, moveSpeed); // 绘制线段和端点 line(Xcont[i], Ycont[i], centerX, centerY); circle(Xcont[i], Ycont[i], 10); } } else { // 未收集满20次点击时显示提示 fill(255); text("点击屏幕收集20个点", 20, 20); } } void mousePressed(){ clickCounter += 1; if(clickCounter <= 20){ Xcont = append(Xcont, mouseX); Ycont = append(Ycont, mouseY); println("已收集点:" + clickCounter + "/20"); } }
关键修改说明
- 清空画布:在
draw()开头添加background(0),避免之前绘制的图形残留,保证移动效果清晰。 - 坐标更新逻辑:用
lerp(当前值, 目标值, 比例)实现平滑移动,moveSpeed控制快慢,取值0~1之间。 - 替代移动方案:如果不想用
lerp,可以直接按固定像素量向中心移动(保证所有点速度一致):float dx = centerX - Xcont[i]; float dy = centerY - Ycont[i]; float dist = sqrt(dx*dx + dy*dy); if(dist > 1){ // 避免距离过近时抖动 Xcont[i] += dx / dist * 1; // 1为每帧移动的像素数 Ycont[i] += dy / dist * 1; } - 交互优化:添加了收集点的提示文字,让用户明确当前操作状态。
内容的提问来源于stack exchange,提问作者Crystallean
相关产品推荐
相关产品推荐

