physics/projects/projectile/index.js
Loic Guegan 8806d5d61b Update
2021-10-07 09:27:52 +02:00

142 lines
2.9 KiB
JavaScript

let t=0;
let vy0=50
let vx0=vy0
let x0=140
let y0=80
let g=9.81
let projectile= function (p){
let width=800
let height=300
let dots=[] // Dots that show the projectile path
p.end=false;
p.setup = function() {
c=p.createCanvas(Math.min(window.innerWidth,width), height);
vy0t=p.createElement('span', '');
katex.render("v_0", vy0t.elt);
r=p.createElement('span', '');
katex.render("\\vec{r}(t)", r.elt);
vt=p.createElement('span', '');
katex.render("v(t)", vt.elt);
vi=p.createElement('span', '');
katex.render("\\vec{i}", vi.elt);
vj=p.createElement('span', '');
katex.render("\\vec{j}", vj.elt);
};
// See explanations in html
function xt(t) {
return x0+vx0*t
}
function yt(t) {
return height - (-1/2 * g * t**2 + vy0 * t + y0)
}
function vx(t) {
return vx0
}
function vy(t) {
return -g * t + vy0
}
let draw_vectors=function(x,y,skiparrow=false){
p.push()
p.stroke(199, 141, 107)
draw_arrow(p,x,y,x+vx(t),y-vy(t),vt,c,skiparrow)
p.stroke(200)
draw_arrow(p,x0,height-y0,x,y,r,c,skiparrow)
p.stroke(121, 199, 107)
draw_arrow(p,app.x0,height-app.y0,app.x0,height-app.y0-50,vj,c,skiparrow,true)
p.stroke(199,119,107)
draw_arrow(p,app.x0,height-app.y0,app.x0+50,height-app.y0,vi,c,skiparrow)
p.stroke(181, 107, 199)
draw_arrow(p,app.x0,height-app.y0,app.x0+app.vx0,height-(app.y0+app.vy0),vy0t,c,skiparrow)
p.pop()
}
p.draw = function() {
p.clear()
let x=xt(t)
let y=yt(t)
// Draw projectile and path
p.push()
p.noStroke()
p.fill(100)
dots.forEach((elt)=>{p.ellipse(elt[0],elt[1],5,5);})
p.fill(0)
p.ellipse(x,y,20,20);
p.pop()
// Draw vectors
draw_vectors(x,y)
p.push()
p.stroke(0)
p.ellipse(app.x0,height-app.y0,8)
p.pop()
// Check simulation state and update it
if(t>50 || (height-y0)<y){
p.end=true
p.noLoop()
}
// Update state
if(!p.end){
t+=0.1
dots.push([x,y])
}
};
p.windowResized = function(){
p.resizeCanvas(Math.min(window.innerWidth,width), height);
}
};
refresh=function(){
t=0
x0=app.x0
y0=app.y0
vx0=app.vx0
vy0=app.vy0
g=app.g
p5Load()
}
project_init=function(){
app = new Vue({
el: '#app',
data :{
x0:x0,
y0:y0,
vy0:vy0,
vx0:vx0,
g:g
},
methods:{
origin_redraw:function(){p5_instance.draw()}
}
})
p5Load()
}