JS实现基于Sketch.js模拟成群游动的蝌蚪运动动画效果【附demo源码下载】

本文实例讲述了JS实现基于Sketch.js模拟成群游动的蝌蚪运动动画效果。分享给大家供大家参考,具体如下:

基于Sketch.js,实现了物体触碰检测(蝌蚪会遇到障碍物以及聪明的躲避鼠标的点击),随机运动,聚集算法等。

已经具备了游戏的基本要素,扩展一下可以变成一个不错的 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>

附:完整实例代码点击此处本站下载

更多关于JavaScript相关内容感兴趣的读者可查看本站专题:《JavaScript动画特效与技巧汇总》、《JavaScript图形绘制技巧总结》、《JavaScript切换特效与技巧总结》、《JavaScript错误与调试技巧总结》、《JavaScript数据结构与算法技巧总结》及《JavaScript数学运算用法总结》

希望本文所述对大家JavaScript程序设计有所帮助。

时间: 2017-08-15

javascript动画之模拟拖拽效果篇

先看看实现效果图, 模拟拖拽最终效果和在桌面上移动文件夹的效果类似 原理介绍 鼠标按下时,拖拽开始.鼠标移动时,被拖拽元素跟着鼠标一起移动.鼠标抬起时,拖拽结束 所以,拖拽的重点是确定被拖拽元素是如何移动的 假设,鼠标按下时,鼠标对象的clientX和clientY分别为x1和x2.元素距离视口左上角x轴和y轴分别为x0和y0 鼠标移动的某一时刻,clientX和clientY分别为x2和y2 所以,元素移动的x轴和y轴距离分别为x2-x1和y2-y1 元素移动后,元素距离视口左上角x轴和y轴的

JS运动框架之分享侧边栏动画实例

本文实例讲述了JS运动框架之分享侧边栏动画实现方法.分享给大家供大家参考.具体实现方法如下: 复制代码 代码如下: <!DOCTYPE html>  <html>      <head>          <meta charset="utf-8">          <title></title>          <style type="text/css">         

js运动动画的八个知识点

今天简单的学了一下js运动动画,记录一下自己的心得体会,分享给大家. 下面是我整理出来的结果. 知识点一:速度动画. 1.首先第一步实现速度运动动画,封装一个函数,用到的知识是setInterval(function(){ 复制代码 代码如下: oDiv.style.left=oDiv.offsetLeft+10+"px"; },30). 对于这里为什么要用到offsetLeft,我特意百度了一下,我得到的有用信息是: a.offsetLeft和left的相同之处都是表示子节点相对于父

用js实现的模拟jquery的animate自定义动画(2.5K)

后来发现还不错.不如继续写下去. 这个版本基本上跟jquery的animate一样了. 我是说效果基本上一样了.(效率还没测试过.): 如果有专业测试人员 帮我测试下. 1:功能说明 兼容主流浏览器. 1:支持回调函数: 2:支持级联动画调用: 3:支持delay动画队列延迟: 4:支持stop停止动画: 5:支持opacity透明度变化: 6:支持+= -= *= /=操作: 7:支持单位操作(px, %); 2:使用说明 jelle(A).animate(B, C, D); A:需要执行动画

javascript动画之圆形运动,环绕鼠标运动作小球

代码如下: 复制代码 代码如下: <script type="text/javascript"> var ball; var mouseX = 100; var mouseY = 100; var angle = 0; var radius = 50; function run(){ if(ball === undefined){ ball = document.createElement("span"); ball.style.position = &

原生javascript实现匀速运动动画效果

本文向大家介绍一个javascript实现的动画.点击开始按钮div会往右移动,点击停止后,div停止移动,再点击则继续移动.请看下面代码: <html> <head> <meta charset="gb2312"> <head> <title>javascript实现的简单动画</title> <style type="text/css"> #mydiv { width:50px;

用js模拟JQuery的show与hide动画函数代码

复制代码 代码如下: //根据ID返回dom元素 var $ = function(id){return document.getElementById(id);} //返回dom元素的当前某css值 var getCss = function(obj,name){ //ie if(obj.currentStyle) { return obj.currentStyle[name]; } //ff else { var style = document.defaultView.getCompute

js弹性势能动画之抛物线运动实例详解

抛物线运动就是:当拖拽结束的时候,我们让当前的元素同时水平运动+垂直运动 在同样的移动距离下,我们鼠标移动的速度快,move方法触发的次数少,相反移动的速度慢,move方法触发的次数就多->浏览器对于每一次的move行为的触发都是由一个最小时间的. 通过观察,我们发现一个事情:水平方向我们盒子在结束拖拽的时候移动的速度和移动的距离没有必然的联系,和开始拖拽的速度也没有必然的联系,只和最后一次即将松开的那一瞬间鼠标的速度是有关系的,最后瞬间鼠标如果移动的快,我们水平运动的距离和速度也是比较大的.-

js 排序动画模拟 冒泡排序

而在某些场景中,队列确实像一支奇兵,可以带来不错的效果,比如配合定时器使用,可以模拟时间差效果 复制代码 代码如下: function createDq(){ var dq = [], size = 0; return { setDq:function(queue){ dq = queue; size = queue.length; }, queue:function(fn){ size ++; dq.push(fn); }, dqueue:function(){ size --; return

js排序动画模拟-插入排序

0 && (t > 0; } //--> [Ctrl+A 全选 注:如需引入外部Js需刷新才能执行]

JS排序算法之冒泡排序,选择排序与插入排序实例分析

本文实例讲述了JS排序算法之冒泡排序,选择排序与插入排序.分享给大家供大家参考,具体如下: 冒泡排序: 对数组的中的数据,依次比较相邻两数的大小. 如果前面的数据大于后面的数据,就交换这两个数. 时间复杂度O(n^2) function bubble(array){ var temp; for(var i=0; i<arr.length; i++){ for(var j=0; j<arr.length; j++){ if(arr[j]>arr[j+1]){ temp = arr[j+1]

js排序与重组的实例讲解

前几天同学发给我一个问题,思路想整理一下,也供大家参考.实际上这道题本质就是考察的是去重与排序的问题.好了闲话少说,上题. function input(req){ if(req<=100){ var arr=[],arr1=[]; for(var i=0;i<req;i++){ var num=parseInt(Math.random()*(1000-1)+1); arr.push(num); if(arr1.indexOf(arr[i])==-1) arr1.push(arr[i]); }

js实现div模拟模态对话框展现URL内容

本文实例讲述了js实现div模拟模态对话框展现URL内容.分享给大家供大家参考,具体如下: <script> function sAlert(str){ var msgw,msgh,bordercolor; msgw=800;//提示窗口的宽度 msgh=600;//提示窗口的高度 titleheight=25 //提示窗口标题高度 bordercolor="#336699";//提示窗口的边框颜色 titlecolor="#99CCFF";//提示窗口

经典排序算法之冒泡排序(Bubble sort)代码

经典排序算法 - 冒泡排序Bubble sort 原理是临近的数字两两进行比较,按照从小到大或者从大到小的顺序进行交换, 这样一趟过去后,最大或最小的数字被交换到了最后一位, 然后再从头开始进行两两比较交换,直到倒数第二位时结束,其余类似看例子 例子为从小到大排序, 原始待排序数组| 6 | 2 | 4 | 1 | 5 | 9 | 第一趟排序(外循环) 第一次两两比较6 > 2交换(内循环) 交换前状态| 6 | 2 | 4 | 1 | 5 | 9 | 交换后状态| 2 | 6 | 4 | 1

JS排序算法之希尔排序与快速排序实现方法

本文实例讲述了JS排序算法之希尔排序与快速排序实现方法.分享给大家供大家参考,具体如下: 希尔排序: 定义一个间隔序列,例如是5,3,1.第一次处理,会处理所有间隔为5的,下一次会处理间隔为3的,最后一次处理间隔为1的元素.也就是相邻元素执行标准插入排序. 在开始最后一次处理时,大部分元素都将在正确的位置,算法就不必对很多元素进行交换,这是比插入元素高级的地方. 时间复杂度O(n*logn) function shellSort(){ var N=arr.length; var h=1; whi

PHP排序算法之冒泡排序(Bubble Sort)实现方法详解

本文实例讲述了PHP排序算法之冒泡排序(Bubble Sort)实现方法.分享给大家供大家参考,具体如下: 基本思想: 冒泡排序是一种交换排序,它的基本思想是:两两比较相邻记录的关键字,如果反序则交换,直到没有反序的记录为止. 最简单排序实现: 我们先来看看在没有学习各种排序方法前经常使用的排序方法(至少我是这样....): //这里使用了类型提示(type hint) array,不熟悉或者不习惯的同学大可去掉,不影响运算结果 function MySort(array &$arr){ $le

js+CSS实现模拟华丽的select控件下拉菜单效果

本文实例讲述了js+CSS实现模拟select控件的下拉菜单效果.分享给大家供大家参考.具体如下: 这是一个JS+CSS技术实现的Select控件效果,模拟出来的,比默认的Select更漂亮,有了这个模板,你修改Select就更方便了,由此你也可以将其制作成CSS下拉菜单,在兼容性方面暂未测试,在IE8下没问题. 运行效果截图如下: 在线演示地址如下: http://demo.jb51.net/js/2015/js-css-select-control-style-codes/ 具体代码如下: