最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

JS實(shí)現(xiàn)基于Sketch.js模擬成群游動(dòng)的蝌蚪運(yùn)動(dòng)動(dòng)畫效果【附demo源碼下載】

 更新時(shí)間:2017年08月18日 11:57:30   作者:陳小峰_iefreer  
這篇文章主要介紹了JS實(shí)現(xiàn)基于Sketch.js模擬成群游動(dòng)的蝌蚪運(yùn)動(dòng)動(dòng)畫效果,涉及Sketch.js插件的使用及HTML5元素的應(yīng)用技巧,并附帶demo源碼供讀者下載參考,需要的朋友可以參考下

本文實(shí)例講述了JS實(shí)現(xiàn)基于Sketch.js模擬成群游動(dòng)的蝌蚪運(yùn)動(dòng)動(dòng)畫效果。分享給大家供大家參考,具體如下:

基于Sketch.js,實(shí)現(xiàn)了物體觸碰檢測(cè)(蝌蚪會(huì)遇到障礙物以及聰明的躲避鼠標(biāo)的點(diǎn)擊),隨機(jī)運(yùn)動(dòng),聚集算法等。

已經(jīng)具備了游戲的基本要素,擴(kuò)展一下可以變成一個(gè)不錯(cuò)的 HTML5 游戲。

演示效果如下:

完整代碼如下:

<!DOCTYPE html>
<html class=" -webkit- js flexbox canvas canvastext webgl no-touch geolocation postmessage websqldatabase indexeddb hashchange history draganddrop websockets rgba hsla multiplebgs backgroundsize borderimage borderradius boxshadow textshadow opacity cssanimations csscolumns cssgradients cssreflections csstransforms csstransforms3d csstransitions fontface generatedcontent video audio localstorage sessionstorage webworkers applicationcache svg inlinesvg smil svgclippaths">
<head>
<meta charset="UTF-8">
<title>HTML5 Preview Panel</title>
<script src="prefixfree.min.js"></script>
<script src="modernizr.js"></script>
<style>
body {
  background-color: #222;
}
</style>
</head>
<body>
<script src="sketch.min.js"></script>
<div id="container">
<canvas class="sketch" id="sketch-0" height="208" width="607"></canvas>
</div>
<script>
var calculateDistance = function(object1, object2) {
  x = Math.abs(object1.x - object2.x);
  y = Math.abs(object1.y - object2.y);
  return Math.sqrt((x * x) + (y * y));
};
var calcMagnitude = function(x, y) {
  return Math.sqrt((x * x) + (y * y));
};
var calcVectorAdd = function(v1, v2) {
  return {
    x: v1.x + v2.x,
    y: v1.y + v2.y
  };
};
var random = function(min, max) {
  return min + Math.random() * (max - min);
};
var getRandomItem = function(list, weight) {
  var total_weight = weight.reduce(function(prev, cur, i, arr) {
    return prev + cur;
  });
  var random_num = random(0, total_weight);
  var weight_sum = 0;
  //console.log(random_num)
  for (var i = 0; i < list.length; i++) {
    weight_sum += weight[i];
    weight_sum = +weight_sum.toFixed(2);
    if (random_num <= weight_sum) {
      return list[i];
    }
  }
  // end of function
};
/***********************
BOID
***********************/
function Boid(x, y) {
  this.init(x, y);
}
Boid.prototype = {
  init: function(x, y) {
    //body
    this.type = "boid";
    this.alive = true;
    this.health = 1;
    this.maturity = 4;
    this.speed = 6;
    this.size = 5;
    this.hungerLimit = 12000;
    this.hunger = 0;
    this.isFull = false;
    this.digestTime = 400;
    this.color = 'rgb(' + ~~random(0, 100) + ',' + ~~random(50, 220) + ',' + ~~random(50, 220) + ')';
    //brains
    this.eyesight = 100; //range for object dectection
    this.personalSpace = 20; //distance to avoid safe objects
    this.flightDistance = 60; //distance to avoid scary objects
    this.flockDistance = 100; //factor that determines how attracted the boid is to the center of the flock
    this.matchVelFactor = 6; //factor that determines how much the flock velocity affects the boid. less = more matching
    this.x = x || 0.0;
    this.y = y || 0.0;
    this.v = {
      x: random(-1, 1),
      y: random(-1, 1),
      mag: 0
    };
    this.unitV = {
      x: 0,
      y: 0,
    };
    this.v.mag = calcMagnitude(this.v.x, this.v.y);
    this.unitV.x = (this.v.x / this.v.mag);
    this.unitV.y = (this.v.y / this.v.mag);
  },
  wallAvoid: function(ctx) {
    var wallPad = 10;
    if (this.x < wallPad) {
      this.v.x = this.speed;
    } else if (this.x > ctx.width - wallPad) {
      this.v.x = -this.speed;
    }
    if (this.y < wallPad) {
      this.v.y = this.speed;
    } else if (this.y > ctx.height - wallPad) {
      this.v.y = -this.speed;
    }
  },
  ai: function(boids, index, ctx) {
    percievedCenter = {
      x: 0,
      y: 0,
      count: 0
    };
    percievedVelocity = {
      x: 0,
      y: 0,
      count: 0
    };
    mousePredator = {
      x: ((typeof ctx.touches[0] === "undefined") ? 0 : ctx.touches[0].x),
      y: ((typeof ctx.touches[0] === "undefined") ? 0 : ctx.touches[0].y)
    };
    for (var i = 0; i < boids.length; i++) {
      if (i != index) {
        dist = calculateDistance(this, boids[i]);
        //Find all other boids close to it
        if (dist < this.eyesight) {
          //if the same species then flock
          if (boids[i].type == this.type) {
            //Alignment
            percievedCenter.x += boids[i].x;
            percievedCenter.y += boids[i].y;
            percievedCenter.count++;
            //Cohesion
            percievedVelocity.x += boids[i].v.x;
            percievedVelocity.y += boids[i].v.y;
            percievedVelocity.count++;
            //Separation
            if (dist < this.personalSpace + this.size + this.health) {
              this.avoidOrAttract("avoid", boids[i]);
            }
          } else {
            //if other species fight or flight
            if (dist < this.size + this.health + boids[i].size + boids[i].health) {
              this.eat(boids[i]);
            } else {
              this.handleOther(boids[i]);
            }
          }
        } //if close enough
      } //dont check itself
    } //Loop through boids
    //Get the average for all near boids
    if (percievedCenter.count > 0) {
      percievedCenter.x = ((percievedCenter.x / percievedCenter.count) - this.x) / this.flockDistance;
      percievedCenter.y = ((percievedCenter.y / percievedCenter.count) - this.y) / this.flockDistance;
      this.v = calcVectorAdd(this.v, percievedCenter);
    }
    if (percievedVelocity.count > 0) {
      percievedVelocity.x = ((percievedVelocity.x / percievedVelocity.count) - this.v.x) / this.matchVelFactor;
      percievedVelocity.y = ((percievedVelocity.y / percievedVelocity.count) - this.v.y) / this.matchVelFactor;
      this.v = calcVectorAdd(this.v, percievedVelocity);
    }
    //Avoid Mouse
    if (calculateDistance(mousePredator, this) < this.eyesight) {
      var mouseModifier = 20;
      this.avoidOrAttract("avoid", mousePredator, mouseModifier);
    }
    this.wallAvoid(ctx);
    this.limitVelocity();
  },
  setUnitVector: function() {
    var magnitude = calcMagnitude(this.v.x, this.v.y);
    this.v.x = this.v.x / magnitude;
    this.v.y = this.v.y / magnitude;
  },
  limitVelocity: function() {
    this.v.mag = calcMagnitude(this.v.x, this.v.y);
    this.unitV.x = (this.v.x / this.v.mag);
    this.unitV.y = (this.v.y / this.v.mag);
    if (this.v.mag > this.speed) {
      this.v.x = this.unitV.x * this.speed;
      this.v.y = this.unitV.y * this.speed;
    }
  },
  avoidOrAttract: function(action, other, modifier) {
    var newVector = {
      x: 0,
      y: 0
    };
    var direction = ((action === "avoid") ? -1 : 1);
    var vModifier = modifier || 1;
    newVector.x += ((other.x - this.x) * vModifier) * direction;
    newVector.y += ((other.y - this.y) * vModifier) * direction;
    this.v = calcVectorAdd(this.v, newVector);
  },
  move: function() {
    this.x += this.v.x;
    this.y += this.v.y;
    if (this.v.mag > this.speed) {
      this.hunger += this.speed;
    } else {
      this.hunger += this.v.mag;
    }
  },
  eat: function(other) {
    if (!this.isFull) {
      if (other.type === "plant") {
        other.health--;
        this.health++;
        this.isFull = true;
        this.hunger = 0;
      }
    }
  },
  handleOther: function(other) {
    if (other.type === "predator") {
      this.avoidOrAttract("avoid", other);
    }
  },
  metabolism: function() {
    if (this.hunger >= this.hungerLimit) {
      this.health--;
      this.hunger = 0;
    }
    if (this.hunger >= this.digestTime) {
      this.isFull = false;
    }
    if (this.health <= 0) {
      this.alive = false;
    }
  },
  mitosis: function(boids) {
    if (this.health >= this.maturity) {
      //reset old boid
      this.health = 1;
      birthedBoid = new Boid(
        this.x + random(-this.personalSpace, this.personalSpace),
        this.y + random(-this.personalSpace, this.personalSpace)
      );
      birthedBoid.color = this.color;
      boids.push(birthedBoid);
    }
  },
  draw: function(ctx) {
    drawSize = this.size + this.health;
    ctx.beginPath();
    ctx.moveTo(this.x + (this.unitV.x * drawSize), this.y + (this.unitV.y * drawSize));
    ctx.lineTo(this.x + (this.unitV.y * drawSize), this.y - (this.unitV.x * drawSize));
    ctx.lineTo(this.x - (this.unitV.x * drawSize * 2), this.y - (this.unitV.y * drawSize * 2));
    ctx.lineTo(this.x - (this.unitV.y * drawSize), this.y + (this.unitV.x * drawSize));
    ctx.lineTo(this.x + (this.unitV.x * drawSize), this.y + (this.unitV.y * drawSize));
    ctx.fillStyle = this.color;
    ctx.shadowBlur = 20;
    ctx.shadowColor = this.color;
    ctx.fill();
  }
};
Predator.prototype = new Boid();
Predator.prototype.constructor = Predator;
Predator.constructor = Boid.prototype.constructor;
function Predator(x, y) {
  this.init(x, y);
  this.type = "predator";
  //body
  this.maturity = 6;
  this.speed = 6;
  this.hungerLimit = 25000;
  this.color = 'rgb(' + ~~random(100, 250) + ',' + ~~random(10, 30) + ',' + ~~random(10, 30) + ')';
  //brains
  this.eyesight = 150;
  this.flockDistance = 300;
}
Predator.prototype.eat = function(other) {
  if (!this.isFull) {
    if (other.type === "boid") {
      other.health--;
      this.health++;
      this.isFull = true;
      this.hunger = 0;
    }
  }
};
Predator.prototype.handleOther = function(other) {
  if (other.type === "boid") {
    if (!this.isFull) {
      this.avoidOrAttract("attract", other);
    }
  }
};
Predator.prototype.mitosis = function(boids) {
  if (this.health >= this.maturity) {
    //reset old boid
    this.health = 1;
    birthedBoid = new Predator(
      this.x + random(-this.personalSpace, this.personalSpace),
      this.y + random(-this.personalSpace, this.personalSpace)
    );
    birthedBoid.color = this.color;
    boids.push(birthedBoid);
  }
};
Plant.prototype = new Boid();
Plant.prototype.constructor = Plant;
Plant.constructor = Boid.prototype.constructor;
function Plant(x, y) {
  this.init(x, y);
  this.type = "plant";
  //body
  this.speed = 0;
  this.size = 10;
  this.health = ~~random(1, 10);
  this.color = 'rgb(' + ~~random(130, 210) + ',' + ~~random(40, 140) + ',' + ~~random(160, 220) + ')';
  //brains
  this.eyesight = 0;
  this.flockDistance = 0;
  this.eyesight = 0; //range for object dectection
  this.personalSpace = 100; //distance to avoid safe objects
  this.flightDistance = 0; //distance to avoid scary objects
  this.flockDistance = 0; //factor that determines how attracted the boid is to the center of the flock
  this.matchVelFactor = 0; //factor that determines how much the flock velocity affects the boid
}
Plant.prototype.ai = function(boids, index, ctx) {};
Plant.prototype.move = function() {};
Plant.prototype.mitosis = function(boids) {
  var growProbability = 1,
    maxPlants = 40,
    plantCount = 0;
  for (m = boids.length - 1; m >= 0; m--) {
    if (boids[m].type === "plant") {
      plantCount++;
    }
  }
  if (plantCount <= maxPlants) {
    if (random(0, 100) <= growProbability) {
      birthedBoid = new Plant(
        this.x + random(-this.personalSpace, this.personalSpace),
        this.y + random(-this.personalSpace, this.personalSpace)
      );
      birthedBoid.color = this.color;
      boids.push(birthedBoid);
    }
  }
};
Plant.prototype.draw = function(ctx) {
  var drawSize = this.size + this.health;
  ctx.fillStyle = this.color;
  ctx.shadowBlur = 40;
  ctx.shadowColor = this.color;
  ctx.fillRect(this.x - drawSize, this.y + drawSize, drawSize, drawSize);
};
/***********************
SIM
***********************/
var boids = [];
var sim = Sketch.create({
  container: document.getElementById('container')
});
sim.setup = function() {
  for (i = 0; i < 50; i++) {
    x = random(0, sim.width);
    y = random(0, sim.height);
    sim.spawn(x, y);
  }
};
sim.spawn = function(x, y) {
  var predatorProbability = 0.1,
    plantProbability = 0.3;
  switch (getRandomItem(['boid', 'predator', 'plant'], [1 - predatorProbability - plantProbability, predatorProbability, plantProbability])) {
    case 'predator':
      boid = new Predator(x, y);
      break;
    case 'plant':
      boid = new Plant(x, y);
      break;
    default:
      boid = new Boid(x, y);
      break;
  }
  boids.push(boid);
};
sim.update = function() {
  for (i = boids.length - 1; i >= 0; i--) {
    if (boids[i].alive) {
      boids[i].ai(boids, i, sim);
      boids[i].move();
      boids[i].metabolism();
      boids[i].mitosis(boids);
    } else {
      //remove dead boid
      boids.splice(i, 1);
    }
  }
};
sim.draw = function() {
  sim.globalCompositeOperation = 'lighter';
  for (i = boids.length - 1; i >= 0; i--) {
    boids[i].draw(sim);
  }
  sim.fillText(boids.length, 20, 20);
};
</script>
</body>
</html>

附:完整實(shí)例代碼點(diǎn)擊此處本站下載。

更多關(guān)于JavaScript相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《JavaScript動(dòng)畫特效與技巧匯總》、《JavaScript圖形繪制技巧總結(jié)》、《JavaScript切換特效與技巧總結(jié)》、《JavaScript錯(cuò)誤與調(diào)試技巧總結(jié)》、《JavaScript數(shù)據(jù)結(jié)構(gòu)與算法技巧總結(jié)》及《JavaScript數(shù)學(xué)運(yùn)算用法總結(jié)

希望本文所述對(duì)大家JavaScript程序設(shè)計(jì)有所幫助。

相關(guān)文章

  • javascript中的事件代理初探

    javascript中的事件代理初探

    本文僅僅起到一個(gè)拋磚引玉的作用,讓大家了解到事件代理的原理而已,jquery中的live和delegate實(shí)現(xiàn)要復(fù)雜的多
    2014-03-03
  • JavaScript獲取瀏覽器窗口尺寸的幾種方法

    JavaScript獲取瀏覽器窗口尺寸的幾種方法

    JavaScript是一種廣泛使用的腳本語言,用于開發(fā)網(wǎng)頁和應(yīng)用程序,在Web開發(fā)中,經(jīng)常需要獲取瀏覽器窗口的尺寸,以便根據(jù)窗口大小進(jìn)行布局或執(zhí)行其他操作,本文將介紹如何使用JavaScript來獲取瀏覽器窗口尺寸,需要的朋友可以參考下
    2023-11-11
  • javascript設(shè)計(jì)模式之解釋器模式詳解

    javascript設(shè)計(jì)模式之解釋器模式詳解

    這篇文章主要介紹了javascript設(shè)計(jì)模式之解釋器模式詳解,當(dāng)有一個(gè)語言需要解釋執(zhí)行,并且可以將該語言中的句子表示為一個(gè)抽象語法樹的時(shí)候,可以考慮使用解釋器模式,需要的朋友可以參考下
    2014-06-06
  • Javascript實(shí)現(xiàn)蘋果懸浮虛擬按鈕

    Javascript實(shí)現(xiàn)蘋果懸浮虛擬按鈕

    本文給大家分享的是使用javascript實(shí)現(xiàn)仿制蘋果的懸浮虛擬按鈕的代碼,非常的簡單,給大家一個(gè)思路,大家可以根據(jù)自己的情況自由擴(kuò)展。
    2016-04-04
  • JS判斷瀏覽器是否支持某一個(gè)CSS3屬性的方法

    JS判斷瀏覽器是否支持某一個(gè)CSS3屬性的方法

    css3表現(xiàn)沖擊最大的就是動(dòng)畫了,因此很有必要去事先判斷瀏覽器是否支持,寫CSS3動(dòng)畫庫就只有部分瀏覽器支持
    2014-10-10
  • 首頁圖片漂浮效果示例代碼

    首頁圖片漂浮效果示例代碼

    圖片漂浮效果想必大家都有見到過吧,一般都是通過js來實(shí)現(xiàn)的,下面為大家介紹的這個(gè)示例也是通過js實(shí)現(xiàn)的
    2014-06-06
  • 微信小程序web-view環(huán)境下H5跳轉(zhuǎn)小程序頁面方法實(shí)例代碼

    微信小程序web-view環(huán)境下H5跳轉(zhuǎn)小程序頁面方法實(shí)例代碼

    微信小程序是一種全新的連接用戶與服務(wù)的方式,它可以在微信內(nèi)被便捷地獲取和傳播,同時(shí)具有出色的使用體驗(yàn),下面這篇文章主要給大家介紹了關(guān)于微信小程序web-view環(huán)境下H5跳轉(zhuǎn)小程序頁面方法的相關(guān)資料,需要的朋友可以參考下
    2022-08-08
  • js對(duì)象淺拷貝和深拷貝詳解

    js對(duì)象淺拷貝和深拷貝詳解

    這篇文章主要為大家詳細(xì)介紹了JavaScript對(duì)象的淺拷貝和深拷貝代碼,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2016-09-09
  • JavaScript實(shí)現(xiàn)QueryString獲取GET參數(shù)的方法

    JavaScript實(shí)現(xiàn)QueryString獲取GET參數(shù)的方法

    本文為大家詳細(xì)介紹下如何通過JavaScript實(shí)現(xiàn)QueryString獲取GET參數(shù),具體實(shí)現(xiàn)如下,感興趣的朋友可以參考下哈,希望對(duì)大家有所幫助
    2013-07-07
  • javascript下用ActiveXObject控件替換word書簽,將內(nèi)容導(dǎo)出到word后打印

    javascript下用ActiveXObject控件替換word書簽,將內(nèi)容導(dǎo)出到word后打印

    由于時(shí)間比較緊,沒多的時(shí)候去學(xué)習(xí)研究上述工具包,現(xiàn)在用javascript操作ActiveXObject控件,用替換word模板中的書簽方式解決。
    2008-06-06

最新評(píng)論

高邑县| 北海市| 长葛市| 介休市| 奎屯市| 吉安市| 平利县| 丰镇市| 沙坪坝区| 枝江市| 昌黎县| 樟树市| 陇南市| 宜兴市| 台州市| 平顶山市| 石渠县| 尚义县| 德惠市| 保山市| 类乌齐县| 阿克| 刚察县| 新乐市| 融水| 女性| 洛扎县| 天水市| 山丹县| 阜南县| 杨浦区| 尼勒克县| 中宁县| 钦州市| 区。| 随州市| 大同市| 新源县| 四会市| 岢岚县| 高陵县|