问题描述
我一直在尝试学习JavaScript中的粒子,因此我大多复制了代码,但仍然无法正常工作。 粒子类内部的碰撞代码不起作用。我试图解决它,但是没有起作用。 粒子应该像水一样流动,并且在与按钮碰撞后应该飞溅并向侧面移动,但是它并没有那样做,只是穿过按钮而没有任何碰撞。 对不起,我的英语不好,谢谢您的帮助。
class Button{
constructor(x,y,width,height,baseX){
this.x=x;
this.y=y;
this.width=width;
this.height=height;
this.baseX=x;
}
update(){
let directionX=2.2;
if((mouse.x<this.x+this.width&&
mouse.x>this.x&&mouse.y<this.y+this.height&&mouse.y>this.y)&&(this.x>this.baseX-50)){
//animate button
this.x-=directionX;
this.width+=directionX;
}
else if(this.x<this.baseX){
this.x+=directionX;
this.width-=directionX;
}
}
draw(){
ctx.fillStyle='blue';
ctx.beginPath();
ctx.fillRect(this.x,this.y,this.width,this.height);
ctx.closePath();
}
}
const buttons=[];
function createButtons(){
for(let i=0;i<5;i++){
let topMargin=208;
let bottomMargin=5;
let x=399;
let y=topMargin+((50+bottomMargin)*i);
let height=50;
let width=200;
buttons.push(new Button(x,height));
}
}
createButtons();
function drawButtons(){
for(let i=0;i<buttons.length;i++){
buttons[i].update();
}
}
//handle water particles
class Particle{
constructor(x,size,weight){
this.x=x;
this.y=y;
this.size=size;
this.weight=weight;
}
update(){
if(this.x>mouse.x-50 &&
this.x<mouse.x+50 &&
this.y>mouse.y+5&&
this.y<mouse.y-5){
this.x-=this.weight;
this.y+=this.weight;
}
for(let i=0;i<buttons.length;i++){
if(this.x<buttons[i].x+buttons[i].width && this.x>buttons[i].x
&& this.y<buttons[i].y+buttons[i].height
&& this.y>buttons[i].y){
this.weight=0;
this.x-=4;
}
else{
this.weight+=0.03;
}
}
if(this.y>canvas.height){
this.y=0-this.size;
this.x=(Math.random()*60)+200;
this.weight=(Math.random()*0.5)+1;
}
this.y+=this.weight;
}
draw(){
ctx.fillStyle='blue';
ctx.beginPath();
ctx.arc(this.x+270,this.size,2*Math.PI);
ctx.fill();
}
}
const particleArray=[];
const numberofParticles=80;
function createParticles(){
for(let i=0;i<numberofParticles;i++){
const x=(Math.random()*60)+200;
const y=(Math.random()*canvas.height);
const size=(Math.random()*20)+5;
const weight=(Math.random()*0.5)+1;
particleArray.push(new Particle(x,weight));
}
}
createParticles();
//animate canvas
function animate(){
ctx.clearRect(0,canvas.width,canvas.height);
for(let i=0;i<particleArray.length;i++){
particleArray[i].update();
particleArray[i].draw();
}
drawButtons();
requestAnimationFrame(animate);
}
animate();
window.addEventListener('resize',function(e){
canvas.width=window.innerWidth;
canvas.height=window.innerHeight;
})
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)