P5js中如何获取touches数组内指定对象的X、Y坐标值?
p5.js多点触摸数值调用解决方案
核心获取方法
直接通过数组下标访问即可:
- 索引为0的触摸点y值:
touches[0].y - 索引为1的触摸点x值:
touches[1].x - 索引为1的触摸点y值:
touches[1].y
注意事项
touches数组长度等于当前识别到的触摸点数量,访问前必须先判断数组长度,避免下标越界报错:
- 要使用索引0的数值,需先判断
touches.length >= 1 - 要使用索引1的数值,需先判断
touches.length >= 2
功能实现代码
下面的代码已经实现了你需要的控制逻辑:用第一个触摸点的y值控制中心圆形的高度,第二个触摸点的x值控制描边粗细,第二个触摸点的y值控制描边颜色。
function setup() { createCanvas(windowWidth, windowHeight); background(200); } function draw() { background(255); let centerX = windowWidth / 2; let centerY = windowHeight / 2; // 预设默认参数,避免没有触摸时图形显示异常 let centerEllipseHeight = 50; let strokeWidth = 3; let strokeColor = 0; // 当存在至少1个触摸点时,用索引0的y值控制中心图形高度 if (touches.length >= 1) { // map函数把触摸y坐标(0到窗口高度)映射为圆形高度10到200的范围,可自行调整 centerEllipseHeight = map(touches[0].y, 0, windowHeight, 10, 200); } // 当存在至少2个触摸点时,用索引1的数值控制描边参数 if (touches.length >= 2) { // 索引1的x值映射为描边粗细1到20 strokeWidth = map(touches[1].x, 0, windowWidth, 1, 20); // 索引1的y值映射为描边灰度值0到255 strokeColor = map(touches[1].y, 0, windowHeight, 0, 255); } // 绘制所有触摸点和连线 for (var i = 0; i < touches.length; i++) { fill(255); strokeWeight(3); stroke(0); ellipse(touches[i].x, touches[i].y, 50, 50); line(touches[i].x, touches[i].y, centerX, centerY); } // 绘制中心受触摸控制的图形 fill(255, 0, 0); stroke(strokeColor); strokeWeight(strokeWidth); ellipse(centerX, centerY, 50, centerEllipseHeight); // 中心定位小圆 fill(255); noStroke(); ellipse(centerX, centerY, 10, 10); } // 阻止默认触摸行为 function mousePressed() { return false; } document.addEventListener('gesturestart', function(e) { e.preventDefault(); });
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.5.2/p5.min.js"></script>
内容的提问来源于stack exchange,提问作者nothingness
相关产品推荐
相关产品推荐

