JS实现基于Sketch.js模拟成群游动的蝌蚪运动动画效果【附demo源码下载】
发布时间 - 2026-01-11 02:51:46 点击率:次本文实例讲述了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程序设计有所帮助。
# JS
# Sketch.js
# 模拟
# 成群游动
# 蝌蚪
# 运动
# 动画
# js运动动画的八个知识点
# javascript动画之圆形运动
# 环绕鼠标运动作小球
# JS运动框架之分享侧边栏动画实例
# 原生javascript实现匀速运动动画效果
# js弹性势能动画之抛物线运动实例详解
# JS实现匀速与减速缓慢运动的动画效果封装示例
# Js实现简单的小球运动特效
# javascript实现10个球随机运动、碰撞实例详解
# JS实现匀速运动的代码实例
# js实现缓冲运动效果的方法
# Javascript 完美运动框架(逐行分析代码
# 让你轻松了运动的原理)
# JS实现的小火箭发射动画效果示例
# 相关内容
# 鼠标
# 感兴趣
# 数据结构
# 给大家
# 点击此处
# 成群
# 更多关于
# 所述
# 程序设计
# 触碰
# 实现了
# 具备了
# 讲述了
# calculateDistance
# var
# function
# height
# width
# calcMagnitude
相关栏目:
【
网站优化151355 】
【
网络推广146373 】
【
网络技术251813 】
【
AI营销90571 】
相关推荐:
制作无缝贴图网站有哪些,3dmax无缝贴图怎么调?
Google浏览器为什么这么卡 Google浏览器提速优化设置步骤【方法】
大连网站制作费用,大连新青年网站,五年四班里的视频怎样下载啊?
Laravel中DTO是什么概念_在Laravel项目中使用数据传输对象(DTO)
Laravel广播系统如何实现实时通信_Laravel Reverb与WebSockets实战教程
免费视频制作网站,更新又快又好的免费电影网站?
猎豹浏览器开发者工具怎么打开 猎豹浏览器F12调试工具使用【前端必备】
如何制作公司的网站链接,公司想做一个网站,一般需要花多少钱?
如何快速完成中国万网建站详细流程?
如何在 React 中条件性地遍历数组并渲染元素
Laravel项目如何进行性能优化_Laravel应用性能分析与优化技巧大全
Laravel如何创建和注册中间件_Laravel中间件编写与应用流程
HTML5段落标签p和br怎么选_文本排版常用标签对比【解答】
网站制作大概要多少钱一个,做一个平台网站大概多少钱?
香港服务器建站指南:免备案优势与SEO优化技巧全解析
zabbix利用python脚本发送报警邮件的方法
历史网站制作软件,华为如何找回被删除的网站?
Laravel如何使用Vite进行前端资源打包?(配置示例)
Java遍历集合的三种方式
php打包exe后无法访问网络共享_共享权限设置方法【教程】
Laravel如何使用Blade组件和插槽?(Component代码示例)
微信小程序 五星评分(包括半颗星评分)实例代码
Laravel如何处理异常和错误?(Handler示例)
深圳网站制作培训,深圳哪些招聘网站比较好?
Laravel API路由如何设计_Laravel构建RESTful API的路由最佳实践
Android Socket接口实现即时通讯实例代码
香港服务器网站测试全流程:性能评估、SEO加载与移动适配优化
谷歌Google入口永久地址_Google搜索引擎官网首页永久入口
新三国志曹操传主线渭水交兵攻略
利用vue写todolist单页应用
手机网站制作与建设方案,手机网站如何建设?
如何注册花生壳免费域名并搭建个人网站?
PHP怎么接收前端传的文件路径_处理文件路径参数接收方法【汇总】
Laravel观察者模式如何使用_Laravel Model Observer配置
Laravel Asset编译怎么配置_Laravel Vite前端构建工具使用
桂林网站制作公司有哪些,桂林马拉松怎么报名?
Android自定义listview布局实现上拉加载下拉刷新功能
如何用AWS免费套餐快速搭建高效网站?
Laravel如何实现文件上传和存储?(本地与S3配置)
Win11怎么关闭资讯和兴趣_Windows11任务栏设置隐藏小组件
详解Nginx + Tomcat 反向代理 负载均衡 集群 部署指南
车管所网站制作流程,交警当场开简易程序处罚决定书,在交警网站查询不到怎么办?
如何在腾讯云免费申请建站?
如何在建站宝盒中设置产品搜索功能?
Laravel集合Collection怎么用_Laravel集合常用函数详解
如何自定义建站之星网站的导航菜单样式?
laravel怎么用DB facade执行原生SQL查询_laravel DB facade原生SQL执行方法
Laravel的HTTP客户端怎么用_Laravel HTTP Client发起API请求教程
Thinkphp 中 distinct 的用法解析
Laravel如何获取当前登录用户信息_Laravel Auth门面使用与Session用户读取【技巧】

