我怎么能随意移动这个三角形?p5.js



由于几天我都在尝试制作三角形的动画,所以我想在画布上随机移动它。我所有的测试都失败了,所以如果你有一些建议,我愿意接受!

我希望我的三角形像自由电子一样在x和y轴上随机移动,将来我希望其他三角形随机移动,当它们相互接触时,它们会反弹,但这是另一步!

我的代码:

let x = 50;
let y = 200;
let y1 = 100;
let y2 = 200
let x1 = 100;
let x2= 150;
let speed = 5;
let startColor;
let endColor;
let amt = 0;


function setup() {
startColor = color("hsl(172, 100%, 50%)");
endColor = color("hsl(335, 100%, 50%)");
createCanvas(windowWidth, 800);
frameRate(45);

}

function draw() {
colorMode(RGB);
background(252, 238, 10);
shape(); // Appel de la function shape
bounce();// appel de la fonction bounce


}

function bounce() {
x = x + speed;
x1 = x1 + speed;
x2 = x2 + speed;
y = y + speed
y1 = y1 + speed
y2 = y2 + speed
if (x2 > windowWidth || x < 0) {
speed = speed * -1;
}
}

function shape() {

if (amt >= 1) {
amt = 0;
let tmpColor = startColor;
startColor = endColor;
endColor = tmpColor;
}
amt += 0.01;
let colorTransition = lerpColor(startColor, endColor, amt);
noStroke();
fill(colorTransition);
triangle(x, y, x1, y1, x2, y2);

}

首先,您有一个代码可以使三角形始终朝同一方向移动。你可以做的是改变你使用的速度:

现在,每次调用bounce都会将三角形移动speed像素。因此,如果在调用shape()之前在draw()中添加以下内容,三角形将开始随机移动少量:

speed = map(random(), 0, 1, -5, 5);

有很多不同的方法可以做到这一点,这里我们使用处理的random()来生成01之间的数字,以及map()来获得-55之间的值。

现在的问题是,您只有一种类型的速度,并且同时适用于轴xy。你想要的可能是speedXspeedY,两个不同的值应用于你职位的两个组成部分。

一旦你尝试这样做,你就会意识到为speedXspeedY设置两个变量不是很方便,你宁愿为你的位置设置一个变量,由两个分量xy组成,并且为你的速度设置相同的变量。这样你就可以做position = position + speed了。这需要重构代码以使用更面向对象的范例。为了学习如何做到这一点,最好的在线资源之一是";代码的性质";播放列表由编码列车youtube频道。

我每天都在工作,听从了你的建议,现在这就是我的产品,谢谢大家!!

let triangle1;
let triangle2;
let triangle3;
let triangle4;
let triangle5;
let speedX;
let speedY;
let startColor;
let endColor;
let amt = 0;

function setup() {
startColor = color("hsl(172, 100%, 50%)");
endColor = color("hsl(335, 100%, 50%)");
createCanvas(windowWidth, 800);
//creer notre triangle
triangle1 = new Triangles(200, 100, 0, 4);
triangle2 = new Triangles(100, 50, 2, 0);
triangle3 = new Triangles(50, 200, -1, 4);
triangle4 = new Triangles(250, 400, 4, 4);
triangle5 = new Triangles(150, 500, 0, 2);
}
function draw() {
colorMode(RGB);
background(252, 238, 10);
triangle1.show();
triangle1.move();
triangle2.show();
triangle2.move();
triangle3.show();
triangle3.move();
triangle4.show();
triangle4.move();
triangle5.show();
triangle5.move();
}

class Triangles {
//configuration de l'objet
constructor(triX, triY, speedX, speedY){
this.x = triX;
this.y = triY;
this.speedX = speedX;
this.speedY = speedY;
}
show(){
if (amt >= 1) {
amt = 0;
let tmpColor = startColor;
startColor = endColor;
endColor = tmpColor;
}
amt += 0.01;
let colorTransition = lerpColor(startColor, endColor, amt);
noStroke();
fill(colorTransition);
noStroke();
triangle(this.x, this.y, this.x + 25, this.y + 40, this.x -25, this.y + 40);
}
move(){
this.x += this.speedX;
this.y += this.speedY;
if(this.x > width || this.x < 0){
this.speedX *= -1;
}
if(this.y > height || this.y < 0){
this.speedY = this.speedY * -1;
}
}
}

最新更新