日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

canvas 小球碰撞

發布時間:2024/8/1 编程问答 35 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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 小球碰撞的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。