小球弹性碰撞
2019獨角獸企業(yè)重金招聘Python工程師標準>>>
小球彈性碰撞
基于webGL的小球彈性碰撞demo
代碼地址:https://github.com/wisdomofgod/ball_elastic_collision/
演示地址:http://htmlpreview.github.io/?https://github.com/wisdomofgod/ball_elastic_collision/blob/master/index.html
小球彈性碰撞:
- 小球設置?:小球位置,速度,角度由random函數(shù)生成,其中角度由x,y軸速度控制;
- 小球顏色?:小球顏色由小球所在位置計算得出,色值 = 小球位置 * 0.5, 同時增加由圓心向外的漸變效果;
- 小球碰撞?:小球碰撞有小球撞擊墻壁與撞擊其他小球兩種情況,有兩個撞擊的彈性參數(shù)決定反彈力。?
片段著色器
在頂點著色器中,設置v_color = gl_Position * 0.5; 在片段著色器中,首先因為我們要畫圓球,所以判斷一下當前插值的點跟球心的距離,插值的時候,是按方形進行插值的,我們只對距離小于等于半徑的點進行著色, 如果距離小于半徑,則設置顏色色值為 v_color + d - 0.2;(為了實現(xiàn)從圓心到邊緣的顏色漸變)
代碼塊
<script id="2d-fragment-shader" type="x-shader/x-fragment">precision mediump float;varying vec4 v_color;void main() {gl_FragColor = v_color;float d = distance(gl_PointCoord, vec2(0.5,0.5));if (d < 0.5) {vec4 color = v_color + d - 0.2;gl_FragColor = color;} else { discard;}}</script>小球撞擊墻體
小球撞擊墻壁,在move函數(shù)中進行判斷,如果撞擊墻壁,則將撞擊方向的速度 v * bounce (撞擊墻壁彈性)
代碼塊
this.balls.forEach(a => {a.x += a.vx;a.y += a.vy;if (a.x > this.R) {a.x = this.R;a.vx *= this.bounce;}if (a.x < this.L) {a.x = this.L;a.vx *= this.bounce;}if (a.y > this.T) {a.y = this.T;a.vy *= this.bounce;}if (a.y < this.B) {a.y = this.B;a.vy *= this.bounce;}});小球之間碰撞
首先通過兩個小球之間的距離,如果距離小于等于小球直徑,則兩小球疊加 小球發(fā)生疊加時,由兩小球坐標計算出兩個小球之間的夾角。 通過夾角計算出,要將兩小球分開的最短距離, 這一距離乘以小球間的彈性,得到小球分開的反向加速度。 將反向加速度加上小球的原有x,y軸速度。 由于速度值大于反向加速度值,所以小球將繼續(xù)往里擠壓直到速度方向與加速度方向一致后,加速分離。因此可以產生擠壓彈開效果。
代碼塊
if (dist <= this.misDist) {//碰撞var angle, tx, ty, ax, ay;angle = Math.atan2(dy, dx);tx = ballA.x + Math.cos(angle) * this.misDist;ty = ballA.y + Math.sin(angle) * this.misDist;ax = (tx - ballB.x) * this.spring;ay = (ty - ballB.y) * this.spring;ballA.vx -= ax;ballA.vy -= ay;ballB.vx += ax;ballB.vy += ay;}轉載于:https://my.oschina.net/wisdomofgod/blog/1626559
總結
- 上一篇: 2019中国电信笔试题——求前后重叠的最
- 下一篇: python twisted框架_twi