Processing中箭头碰撞墙壁边缘时如何根据运动方向切换朝向及图片
实现逻辑说明
你需要根据箭头X、Y轴速度的正负组合判断当前运动方向,每次反弹后速度符号变化时同步切换对应朝向的图片即可,修改后的完整代码如下:
主程序代码
Arrows bob; void setup() { size(700, 700); bob = new Arrows(30, 350); } void draw() { background(255); bob.update(); }
Arrows类代码
class Arrows { int x; int y; int speedX = 4; int speedY = 4; PImage arrowRightDown, arrowLeftDown, arrowLeftUp, arrowRightUp; // 四个图片对应四个朝向:右下、左下、左上、右上,可根据你实际的图片资源调整对应关系 //构造函数 Arrows(int x, int y) { this.x = x; this.y = y; // 加载四个方向的箭头图片 arrowRightDown = loadImage("Arrow1.png"); arrowLeftDown = loadImage("Arrow2.png"); arrowLeftUp = loadImage("Arrow3.png"); arrowRightUp = loadImage("Arrow4.png"); } void update() { move(); // 先更新位置和速度 render(); // 再根据最新的速度方向渲染对应图片 } void render() { PImage currentImg; // 根据speedX和speedY的正负判断当前运动方向,选择对应图片 if (speedX > 0 && speedY > 0) { currentImg = arrowRightDown; // 右下 } else if (speedX < 0 && speedY > 0) { currentImg = arrowLeftDown; // 左下 } else if (speedX < 0 && speedY < 0) { currentImg = arrowLeftUp; // 左上 } else { currentImg = arrowRightUp; // 右上 } image(currentImg, this.x, this.y); } void move() { x += speedX; y += speedY; // 左右边缘碰撞反弹 if(x < 0 || x > (width - 50)) { speedX *= -1; } // 上下边缘碰撞反弹 if(y < 0 || y > (height - 50)) { speedY *= -1; } } }
自定义调整说明
如果你的四个箭头图片和上述的方向对应关系不符,直接修改render方法里每个判断分支对应的图片变量即可,不需要调整其他逻辑。另外代码里的碰撞边界width-50/height-50是默认你的箭头图片尺寸为50px,如果你的图片尺寸不同可以改成对应数值。
内容的提问来源于stack exchange,提问作者Dane Whitman
相关产品推荐
相关产品推荐

