I’m making a 3D physics engine and I need to add balls when I press a button, but whenever I click it, everything goes blank.
Here’s the code for the loop, event, and Ball object.
Loop: Cleares mesh, does physics and draws, solves collisions, updates mesh, and finally draws it.
initGL()
function loop(){
//clear to animate
mesh.verts=[
]
mesh.inds=[]
mesh.ind=0
//do physics math
balls.forEach(ball => {
//draw sphere
ball.draw()
ball.phys()
})
//collisions
for (let i = 0; i < substeps; i++){
balls.forEach(ball => {
ball.collwall()
ball.collballs()
})
}
//update the WebGL vertex array buffer and index array buffer
mesh.update()
runGLFrame()
requestAnimationFrame(loop)
}
requestAnimationFrame(loop)
Event: Adds ball, updates mesh, clear mesh, draw all balls, updates mesh.
balls.push(new Ball(5,5,0,0,0,0,1,0,1,1,1,0.8))
//update the WebGL vertex array buffer and index array buffer
mesh.update()
//clear to animate
mesh.verts=[
]
mesh.inds=[]
mesh.ind=0
balls.forEach(ball => {
ball.draw()
})
mesh.update()
Ball constructor: Initializes the ball object and draws a sphere.
constructor(x,y,z,vx,vy,vz,rad,r,g,b,w,bons){
//sphere number
this.sn=balls.length
//current pos.
this.p={x,y,z}
//past pos.
this.pp={x:x-vx,y:y-vy,z:z-vz}
//velocity
this.v={x:vx,y:vy,z:vz}
//weight
this.w=w
//bounciness
this.b=bons
//radius
this.rad=rad
//color
this.c={r,g,b}
//add sphere to mesh, vertices and indices
mesh.addSphere(20,20,x,y,z,rad,r,g,b)
}
It was supposed to create a ball at 0,5,0, but instead it cleared everything. I copied the clear mesh code to the event to try to copy the thing that happens when I initialize it (before the loop and event) but it still doesn't work.