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

P5.js如何实现两个发射点分别触发朝鼠标位置发射圆形子弹

P5.js新增键盘触发第二发射点修改方案

先修复现有代码语法问题

你当前代码末尾多了一个多余的闭合大括号,直接删除即可避免运行报错。

核心修改点

  • 新增keyPressedP5.js内置事件函数,绑定你需要的触发按键(示例用空格键,可自行替换)
  • 第二发射点直接取你Player类里已经绘制的第二个圆形坐标:player.x + 50、player.y,作为子弹生成的初始坐标传入Bullet构造函数即可
  • 可选优化:增加子弹超出画布自动销毁逻辑,避免内存占用持续升高

注:原代码Bullet类的show方法里误写了两个circle绘制逻辑,会导致每颗子弹显示两个圆形,我在修改版里已经修正为单颗子弹只显示一个圆形,如果你需要特殊子弹样式可以自行调整。

修改后完整代码

var bullets = [];
// 定义发射点偏移量,方便后续统一调整位置
const SECOND_GUN_OFFSET = 50;

function setup() {
    createCanvas(600, 600);
    player = new Player();
}

function draw() {
    background(51);
    player.show();

    // 倒序遍历删除超出画布的子弹,避免索引错乱
    for (let i = bullets.length - 1; i >= 0; --i) {
        bullets[i].toMouse();
        bullets[i].show();
        // 超出画布范围就销毁子弹
        if (bullets[i].x < -10 || bullets[i].x > width + 10 || bullets[i].y < -10 || bullets[i].y > height + 10) {
            bullets.splice(i, 1);
        }
    }
}

// 鼠标点击触发主发射点射击
function mousePressed() {
    if (mouseX != player.x || mouseY != player.y) {
        bullets.push(new Bullet(mouseX, mouseY, player.x, player.y))
    }
}

// 键盘按键触发第二发射点射击,示例用空格键(keyCode=32),可自行替换为其他按键
function keyPressed() {
    if (keyCode === 32) {
        let secondGunX = player.x + SECOND_GUN_OFFSET;
        let secondGunY = player.y;
        if (mouseX != secondGunX || mouseY != secondGunY) {
            bullets.push(new Bullet(mouseX, mouseY, secondGunX, secondGunY))
        }
    }
}

function Bullet(X, Y, PX, PY) {
    this.speed = 5;
    this.x = PX;
    this.y = PY;
    this.dir = createVector(X - PX, Y - PY).normalize()
    this.r = 7;

    this.show = function() {
        fill(255, 255, 0);
        stroke(128, 128, 0);
        circle(this.x, this.y, this.r);
    }
    this.toMouse = function() {
        this.x += this.dir.x * this.speed;
        this.y += this.dir.y * this.speed;
    }
}

function Player() {
    this.x = width / 2;
    this.y = 450;
    this.r = 20;
    this.speed = 4;
    this.show = function() {
        fill(0, 255, 0);
        stroke(0, 128, 0);
        circle(this.x, this.y, this.r);
        circle(this.x + SECOND_GUN_OFFSET, this.y, this.r);
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 04:54:02