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

在p5.js中追踪鼠标位置:实现椭圆追逐/逃离鼠标的状态判断

没问题,这在p5.js里实现起来超直观,我给你拆解一下最简的实现步骤,附带完整可运行的代码示例:

核心实现思路
  • 直接用p5.js内置的mouseX和mouseY变量获取鼠标位置,这是最简便的方式,无需额外监听鼠标事件
  • 通过计算椭圆与鼠标的距离变化,判断椭圆是朝向还是远离鼠标,以此更新movingTowardsMouse布尔变量
  • 根据movingTowardsMouse的值,动态设置beast.message的内容,最后在画布上显示出来
完整代码示例
let beast;

function setup() {
  createCanvas(600, 400);
  // 初始化beast对象,包含位置、移动速度、消息文本和状态变量
  beast = {
    x: width / 2,
    y: height / 2,
    speed: 3,
    message: '',
    movingTowardsMouse: false
  };
}

function draw() {
  background(220);
  
  // 计算椭圆中心到鼠标的向量
  const dx = mouseX - beast.x;
  const dy = mouseY - beast.y;
  const currentDistance = sqrt(dx * dx + dy * dy);
  
  // 避免距离过近时出现抖动
  if (currentDistance > 10) {
    // 归一化方向向量(确保移动速度稳定)
    const dirX = dx / currentDistance;
    const dirY = dy / currentDistance;
    
    // 这里默认实现追逐逻辑,若要切换逃离,只需把加号改成减号即可
    const newX = beast.x + dirX * beast.speed;
    const newY = beast.y + dirY * beast.speed;
    
    // 计算移动后的新距离,判断是否朝向鼠标
    const newDistance = sqrt((mouseX - newX) ** 2 + (mouseY - newY) ** 2);
    beast.movingTowardsMouse = newDistance < currentDistance;
    
    // 更新椭圆位置
    beast.x = newX;
    beast.y = newY;
  }
  
  // 根据状态更新消息文本
  beast.message = beast.movingTowardsMouse ? 'Chasing mouse' : 'Fleeing mouse';
  
  // 绘制椭圆
  fill(255, 100, 100);
  ellipse(beast.x, beast.y, 50, 50);
  
  // 绘制消息文本
  fill(0);
  textSize(16);
  textAlign(CENTER);
  text(beast.message, width / 2, 30);
}
关键细节解释
  • 获取鼠标位置:p5.js在draw()循环中会自动更新mouseX和mouseY,直接调用就能拿到当前鼠标在画布上的坐标,这是最省心的方式。
  • 状态判断逻辑:通过比较椭圆移动前后到鼠标的距离,距离变小就说明是在追逐(movingTowardsMouse = true),变大则是逃离。这种方式不需要复杂的向量点积,简单易懂。
  • 扩展玩法:如果需要手动切换追逐/逃离状态,可以加个键盘事件,比如按空格键反转移动方向:
    function keyPressed() {
      if (key === ' ') {
        beast.speed *= -1;
      }
    }
    
    这样切换后,movingTowardsMouse会自动更新对应的状态,消息文本也会跟着变。

内容的提问来源于stack exchange,提问作者D.Quinlan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 09:38:41