canvas 小球碰撞
生活随笔
收集整理的這篇文章主要介紹了
canvas 小球碰撞
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
試著用面向對象的方式用canvas去實現一些東西,
主要代碼
function Bubble() {}; //構造函數Bubble.prototype = {init: function () { //基本配置this.x = random(0, w); //小球x軸初始位置this.y = random(0, h); //小球y軸初始位置this.r = random(20, 100); //小球的半徑范圍this.color = 'rgba(' + random(0, 255) + ',' + random(0, 255) + ',' + random(0, 255) + ',' + random(0.1, 1) +')';this.vx = random(-1, 1);this.vy = random(-1, 1);this.isMove = false},draw: function () { //繪制小球canCon.beginPath(); //把筆抬起來,beginPath() 方法開始一條路徑,或重置當前的路徑。canCon.fillStyle = this.color;canCon.arc(this.x, this.y, this.r, 0, Math.PI * 2); //圓心的位置,xy,半徑,畫圓canCon.fill();},move: function () {if(this.isMove) {this.isMove = falsereturn;}this.x += this.vx;this.y += this.vy;// 檢測小球與小球碰撞var isCollision = collision(this);if (!isCollision) {}//檢測小球與邊框碰撞if (this.x - this.r < 0 || this.x + this.r > w) {this.vx = -this.vx}if (this.y - this.r < 0 || this.y + this.r > h) {this.vy = -this.vy}this.draw();}}function collision (c_ball) {var find = falsevar isCollision = falsefor (var ball of aBubble) {if(ball != c_ball) {var dxv = c_ball.x + c_ball.vx - (ball.x + ball.vx);var dyv = c_ball.y + c_ball.vy - (ball.y + ball.vy);var distance = Math.sqrt(dxv * dxv + dyv * dyv);if (distance <= (c_ball.r + ball.r)) {var dvx = c_ball.vx - ball.vx;var dvy = c_ball.vy - ball.vy;var dx = c_ball.x - ball.x;var dy = c_ball.y - ball.y;var xx_yy = dx * dx + dy * dy;var v_dvx = (dvx * dx * dx + dvy * dx * dy) / xx_yy;var v_dvy = (dvy * dy * dy + dvx * dx * dy) / xx_yy;c_ball.vx = checkSpeed(c_ball.vx - v_dvx);c_ball.vy = checkSpeed(c_ball.vy - v_dvy);ball.vx = checkSpeed(ball.vx + v_dvx);ball.vy = checkSpeed(ball.vy + v_dvy);if (find) {//避免當前循環重復移動ball.isMove = true//避免閃爍ball.draw();}isCollision = true}} else {find = true}}return isCollision;}源碼在這里
https://download.csdn.net/download/shishuwei111/11244810
總結
以上是生活随笔為你收集整理的canvas 小球碰撞的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Oracle数据库索引底层实现原理笔记
- 下一篇: 设置ctfmon.exe自动启动