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程序设计有所帮助。

(0)

相关推荐

  • javascript动画之模拟拖拽效果篇

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

  • 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

  • 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 = &

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

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

  • 用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实现的模拟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:需要执行动画

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

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

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

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

  • js运动动画的八个知识点

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

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

    本文实例讲述了JS实现基于Sketch.js模拟成群游动的蝌蚪运动动画效果.分享给大家供大家参考,具体如下: 基于Sketch.js,实现了物体触碰检测(蝌蚪会遇到障碍物以及聪明的躲避鼠标的点击),随机运动,聚集算法等. 已经具备了游戏的基本要素,扩展一下可以变成一个不错的 HTML5 游戏. 演示效果如下: 完整代码如下: <!DOCTYPE html> <html class=" -webkit- js flexbox canvas canvastext webgl no-

  • Asp.net(C#)读取数据库并生成JS文件制作首页图片切换效果(附demo源码下载)

    本文实例讲述了Asp.net(C#)读取数据库并生成JS文件制作首页图片切换效果的方法.分享给大家供大家参考,具体如下: using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Text; using System.IO; public partial

  • jquery插件jquery.LightBox.js实现点击放大图片并左右点击切换效果(附demo源码下载)

    本文实例讲述了jquery插件jquery.LightBox.js实现点击放大图片并左右点击切换效果.分享给大家供大家参考,具体如下: 该插件乃文章作者所写,目的在于提升作者的js能力,也给一些js菜鸟在使用插件时提供一些便利,老鸟就悠然地飞过吧. 此插件旨在实现目前较为流行的点击放大图片并左右点击切换图片的效果,您可以根据自己的实际需求来设置是否添加左右切换图片的效果.整体代码如下: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transit

  • Java基于装饰者模式实现的图片工具类实例【附demo源码下载】

    本文实例讲述了Java基于装饰者模式实现的图片工具类.分享给大家供大家参考,具体如下: ImgUtil.java: /* * 装饰者模式实现图片处理工具类 * 类似java的io流 - * Img类似低级流可以独立使用 * Press和Resize类似高级流 * 需要依赖于低级流 */ package util; import java.io.File; import java.util.List; /** * 图片工具类(装饰者)和图片(被装饰者)的公共接口 * @author xlk */

  • jQuery模拟完美实现经典FLASH导航动画效果【附demo源码下载】

    本文实例讲述了jQuery模拟实现经典FLASH导航动画效果的方法.分享给大家供大家参考,具体如下: 一.前言: FLASH在中国互联网发展初期的时候非常的热,各种各样的矢量造型和动作,加上专门配制的音效,让很多人眼前一亮,并且让很多人迷上了这种新兴的媒体,那时候兴起了很多大大小小的专门发布FLASH的网站,印象中记得的像"FLASH闪吧"."FLASH帝国"."闪客天地"等这些都是很火很热的网站,在当时盛极一时,由此也产生了一大批的专门从事FL

  • jQuery模拟实现的select点击选择效果【附demo源码下载】

    本文实例讲述了jQuery模拟实现的select点击选择效果.分享给大家供大家参考,具体如下: 有时候有些HTML元素无法让我们用样式控制进行控制,但是射鸡师或是客户的需求就是需要这种效果,还要让每个浏览器都显示同样的效果,这时候就会让我们这些所谓的前端攻城师很蛋疼,客户会认为交了点钱不让你折腾些东西,以为你是没做事的.面对这些对技术一窍不通的客户,技术对于他们来说就是一坨屎,以为我们都是用意念来写代码做程序的,所以都把我们的劳动成果看作是廉价得像是简单的拉出一泡屎而已. 虽然很喜欢什么都没有修

  • JS图片延迟加载插件LazyImgv1.0用法分析【附demo源码下载】

    本文实例讲述了JS图片延迟加载插件LazyImgv1.0用法.分享给大家供大家参考,具体如下: 注:LazyImg 必须定义lazy-data属性,属性值是src的图片路径 引入JS文件: <script type="text/javascript" src="js/lazyImg.v1.0.js"></script> 默认情况下: 在IMG中满足以任何一个条件,都会加载图片: 1.没有class属性 2.如果有class属性并且属性中不包含

  • php实现压缩合并js的方法【附demo源码下载】

    本文实例讲述了php实现压缩合并js的方法.分享给大家供大家参考,具体如下: test.php文件如下: require_once('jsmin.php'); $files = glob("js/*.js"); $js = ""; foreach($files as $file) { $js .= JSMin::minify(file_get_contents($file)); } file_put_contents("combined.js",

  • JS基于ocanvas插件实现的简单画板效果代码(附demo源码下载)

    本文实例讲述了JS基于ocanvas插件实现的简单画板效果.分享给大家供大家参考,具体如下: 使用ocanvas做了个简单的在线画板. ocanvas参考:http://ocanvas.org/ 效果如下: 主要代码如下: <!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> <title>oCanvas Example</title> <meta na

  • jQuery悬停文字提示框插件jquery.tooltipster.js用法示例【附demo源码下载】

    本文实例讲述了jQuery悬停文字提示框插件jquery.tooltipster.js用法.分享给大家供大家参考,具体如下: 运行效果截图如下: index.html页面: <!DOCTYPE html> <html lang="en"> <head> <title>jQuery Tooltips悬停文字提示框效果</title> <meta charset="utf-8" /> <lin

随机推荐