声明:本文为原创文章,如需转载,请注明来源WAxes,谢谢!

  昨天上班的时候闲着无事,就用Canvas写了个桌球游戏来玩玩。。。。所以就拿这游戏上来水一发。或许对一些刚学canvas的人有帮助。

  话说这只是一个简单的DEMO。游戏性,游戏规则什么的我都没怎么考虑,如果有兴趣细化的朋友可以细化一下,比如细化一下规则,游戏开关,加个声音,细化一下进球检测,更严谨甚至可以去查下击球力度、桌面真实摩擦力等来把游戏弄的更像游戏。我只是给个编程思路哈,随便坐个DEMO而已,玩起来估计还是不会很爽快的~~

    桌球游戏

  整个桌球游戏就两个类,一个是球,一个是辅助瞄准线。如果想把改游戏弄的更复杂,还可以再抽象一个形状类,用于检测球与边角的碰撞以及进球。我做的这个游戏采取了最简单的墙壁碰撞检测,所以没有进行球与不规则形状的碰撞检测,如果想玩更复杂的碰撞,可以戳 关于简单的碰撞检测 岑安大大讲的还是很好的。好,接下来就一步一步来:

  【球】

  先贴代码:

  1. var Ball = function(x , y , ismine){
  2. this.x = x;
  3. this.y = y;
  4. this.ismine = ismine;
  5. this.oldx = x;
  6. this.oldy = y;
  7. this.vx = 0;
  8. this.vy = 0;
  9. this.radius = ballRadius;
  10. this.inhole = false;this.moving = true;
  11. }
  12. Ball.prototype = {
  13. constructor:Ball,
  14. _paint:function(){
  15. var b = this.ismine?document.getElementById("wb") : document.getElementById("yb")
  16. if(b.complete) {
  17. ctx.drawImage(b , this.x-this.radius , this.y-this.radius , 2*this.radius , 2*this.radius);
  18. }
  19. else {
  20. b.onload = function(){
  21. ctx.drawImage(b , this.x-this.radius , this.y-this.radius , 2*this.radius , 2*this.radius);
  22. }
  23. }
  24. },
  25. _run:function(t){
  26. this.oldx = this.x;
  27. this.oldy = this.y;
  28.  
  29. this.vx = Math.abs(this.vx)<0.1? 0 : (this.vx>0? this.vx-mcl*t : this.vx+mcl*t);
  30. this.vy = Math.abs(this.vy)<0.1? 0 : (this.vy>0? this.vy-mcl*t : this.vy+mcl*t);
  31. // this.vx += this.vx>0? -mcl*t : mcl*t;
  32. // this.vy += this.vy>0? -mcl*t : mcl*t;
  33.  
  34. this.x += t * this.vx * pxpm;
  35. this.y += t * this.vy * pxpm;
  36.  
  37. if((this.x<50 && this.y<50) || (this.x>370 && this.x<430 && this.y<50) || (this.x > 758 && this.y<50) || (this.x<46 && this.y>490) || (this.x>377 && this.x<420 && this.y>490) || (this.x > 758 && this.y>490)){
  38. this.inhole = true;
  39. if(this.ismine){
  40. var that = this;
  41. setTimeout(function(){
  42. that.x = 202;
  43. that.y = canvas.height/2;
  44. that.vx = 0;
  45. that.vy = 0;
  46. that.inhole = false;
  47. } , 500)
  48. }
  49. else {
  50. document.getElementById("shotNum").innerHTML = parseInt(document.getElementById("shotNum").innerHTML)+1
  51. }
  52. }
  53. else {
  54. if(this.y > canvas.height - (ballRadius+tbw) || this.y < (ballRadius+tbw)){
  55. this.y = this.y < (ballRadius+tbw) ? (ballRadius+tbw) : (canvas.height - (ballRadius+tbw));
  56. this.derectionY = !this.derectionY;
  57. this.vy = -this.vy*0.6;
  58. }
  59. if(this.x > canvas.width - (ballRadius+tbw) || this.x < (ballRadius+tbw)){
  60. this.x = this.x < (ballRadius+tbw) ? (ballRadius+tbw) : (canvas.width - (ballRadius+tbw));
  61. this.derectionX = !this.derectionX;
  62. this.vx = -this.vx*0.6;
  63. }
  64. }
  65. this._paint();
  66.  
  67. if(Math.abs(this.vx)<0.1 && Math.abs(this.vy)<0.1){
  68. this.moving = false;
  69. }
  70. else {
  71. this.moving = true;
  72. }
  73. }
  74. }

  球类的属性:x,y球的位置,vx,vy球的水平速度以及求得垂直速度,ismine代表是白球还是其他球(不同球在_paint方法中绘制的图片不一样),oldx,oldy用于保存球的上一帧位置,不过暂时还没用上,应该有用吧。_paint方法没什么好说的,_run方法就是跟踪小球位置,根据小球每一帧的时间来算出小球的位移增量以及速度增量,mcl和pxpm都是常量,mcl是摩擦力,pxpm是大概算个像素和现实转换比例。。。。然后就是碰撞检测,这个很容易理解了,就计算小球的位置有没有超过边界,超过了就反弹。不过这种碰撞检测很不严谨,如果真要做游戏建议用更复杂一些的。还有就是根据小球的速度来让小球静止。

  【辅助线】

  1. var dotLine = function(x0,y0,x1,y1){
  2. this.x0 = this.x0;
  3. this.y0 = this.y0;
  4. this.x1 = this.x1;
  5. this.y1 = this.y1;
  6. this.dotlength = 3;
  7. this.display = false;
  8. }
  9. dotLine.prototype = {
  10. constructor:dotLine,
  11. _ready:function(){
  12. this.length = Math.sqrt(Math.pow(this.y1 - this.y0 , 2)+Math.pow(this.x1 - this.x0 , 2));
  13. this.dotNum = Math.ceil(this.length/this.dotlength);
  14. },
  15. _paint:function(){
  16. this._ready();
  17. xadd = this.dotlength*(this.x1 - this.x0)/this.length;
  18. yadd = this.dotlength*(this.y1 - this.y0)/this.length;
  19. ctx.save();
  20. ctx.beginPath();
  21. for(var i=1;i<=this.dotNum;i++){
  22. if(i%2!==0){
  23. ctx.moveTo(this.x0+(i-1)*xadd , this.y0+(i-1)*yadd);
  24. ctx.lineTo(this.x0+i*xadd , this.y0+i*yadd);
  25. }
  26. }
  27. ctx.strokeStyle = "#FFF";
  28. ctx.stroke();
  29. ctx.beginPath();
  30. ctx.arc(this.x1 , this.y1 , ballRadius-2 , 0 , 2*Math.PI);
  31. ctx.stroke();
  32. ctx.restore();
  33. }
  34. }

就是画虚线,这个比较简单了,获取鼠标的位置和白球位置,然后在两者之间隔一段距离画条线,然后就成虚线了。

  【多球碰撞检测】

  1. function collision(){
  2. for(var i=0;i<balls.length;i++){
  3. for(var j=0;j<balls.length;j++){
  4. var b1 = balls[i],b2 = balls[j];
  5. if(b1 !== b2 && !b1.inhole && !b2.inhole){
  6. var rc = Math.sqrt(Math.pow(b1.x - b2.x , 2) + Math.pow(b1.y - b2.y , 2));
  7. if(Math.ceil(rc) < (b1.radius + b2.radius)){
  8. if(!b1.moving && !b2.moving) return;
  9. //获取碰撞后的速度增量
  10. var ax = ((b1.vx - b2.vx)*Math.pow((b1.x - b2.x) , 2) + (b1.vy - b2.vy)*(b1.x - b2.x)*(b1.y - b2.y))/Math.pow(rc , 2)
  11. var ay = ((b1.vy - b2.vy)*Math.pow((b1.y - b2.y) , 2) + (b1.vx - b2.vx)*(b1.x - b2.x)*(b1.y - b2.y))/Math.pow(rc , 2)
  12.                 //将速度增量赋给碰撞小球
  13. b1.vx = b1.vx-ax;
  14. b1.vy = b1.vy-ay;
  15. b2.vx = b2.vx+ax;
  16. b2.vy = b2.vy+ay;
  17.                 //修正小球碰撞距离
  18. var clength = ((b1.radius+b2.radius)-rc)/2;
  19. var cx = clength * (b1.x-b2.x)/rc;
  20. var cy = clength * (b1.y-b2.y)/rc;
  21. b1.x = b1.x+cx;
  22. b1.y = b1.y+cy;
  23. b2.x = b2.x-cx;
  24. b2.y = b2.y-cy;
  25. }
  26. }
  27. }
  28. }
  29. }

  对所有小球进行遍历,计算两个小球的球心距离,如果小于两小球的半径和,则说明发生了碰撞。如果两个小球都是静止的,就不进行碰撞检测,否则进行计算碰撞后的速度增量,碰撞速度增量的求法可以直接看 小球碰撞的算法设计 ,里面讲的挺详细的,综合起来就得出了上面那一串式子了。

  将速度增量赋给碰撞小球。因为两个球碰撞那一帧,两个球是有部分重叠的,所以得进行位置修正,不然小球会一直处于碰撞然后就黏在一起了,位置修正的原理也简单,算出两球的球心距离,通过勾股定理计算出两球的重叠区域的宽度,然后把宽度除于2后赋给小球新的位置,新的位置就是两个球的半径刚好等于球心距。

  【鼠标动作】

  1. canvas.addEventListener("mousedown" , function(){
  2. if(balls[0].moving) return;
  3.  
  4. document.querySelector(".shotPower").style.display = "block";
  5. document.querySelector(".shotPower").style.top = balls[0].y-60 + "px";
  6. document.querySelector(".shotPower").style.left = balls[0].x-40 +"px";
  7. document.getElementById("pow").className = "animate";
  8. var x = event.clientX + document.body.scrollLeft + document.documentElement.scrollLeft - document.querySelector(".view").offsetLeft;
  9. var y = event.clientY + document.body.scrollTop + document.documentElement.scrollTop - document.querySelector(".view").offsetTop;
  10. dotline.display = true;
  11. dotline.x0 = balls[0].x;
  12. dotline.y0 = balls[0].y;
  13. dotline.x1 = x;
  14. dotline.y1 = y;
  15.  
  16. window.addEventListener("mouseup" , muHandle , false);
  17. window.addEventListener("mousemove" , mmHandle , false);
  18.  
  19. function mmHandle(){
  20. var x = event.clientX + document.body.scrollLeft + document.documentElement.scrollLeft - document.querySelector(".view").offsetLeft;
  21. var y = event.clientY + document.body.scrollTop + document.documentElement.scrollTop - document.querySelector(".view").offsetTop;
  22. dotline.x1 = x;
  23. dotline.y1 = y;
  24. }
  25. function muHandle(){
  26. var x = event.clientX + document.body.scrollLeft + document.documentElement.scrollLeft - document.querySelector(".view").offsetLeft;
  27. var y = event.clientY + document.body.scrollTop + document.documentElement.scrollTop - document.querySelector(".view").offsetTop;
  28.  
  29. var angle = Math.atan((y - balls[0].y)/(x - balls[0].x));
  30. var h = document.getElementById("pow").offsetHeight/document.getElementById("powbar").offsetHeight;
  31. var v = 60*h;
  32. document.getElementById("pow").style.height = h*100+"%"
  33.  
  34. balls[0].vx = x - balls[0].x>0 ? v*Math.abs(Math.cos(angle)) : -v*Math.abs(Math.cos(angle));
  35. balls[0].vy = y - balls[0].y>0 ? v*Math.abs(Math.sin(angle)) : -v*Math.abs(Math.sin(angle));
  36.  
  37. document.getElementById("pow").className = "";
  38.  
  39. window.removeEventListener("mouseup" , muHandle , false);
  40. window.removeEventListener("mousemove" , muHandle , false);
  41. dotline.display = false;
  42. document.querySelector(".shotPower").style.display = "none";
  43. }
  44. },false);

  鼠标动作也比较简单,有js基础的基本上都没问题,就是鼠标按下后计算鼠标位置,然后产生辅助虚线,鼠标移动后修改辅助虚线的终点位置。鼠标按下的时候旁边产生一个力量计,我就只用用animation做动画了,然后鼠标按键抬起时通过计算力量计的大小来确定白球的速度,然后再分解成水平速度以及垂直速度赋给白球。同时取消鼠标移动以及鼠标抬起的事件绑定,把辅助虚线以及力量计隐藏。

  【动画舞台】

  1. function animate(){
  2. ctx.clearRect(0,0,canvas.width,canvas.height)
  3. var t1 = new Date();
  4. var t = (t1 - t0)/1000;
  5.  
  6. collision();
  7. balls.foreach(function(){
  8. if(!this.inhole) this._run(t);
  9. });
  10. if(dotline.display){
  11. dotline.x0 = balls[0].x;
  12. dotline.y0 = balls[0].y;
  13. dotline._paint();
  14. }
  15.  
  16. t0 = t1;
  17. if(!animateStop){
  18. if("requestAnimationFrame" in window){
  19. requestAnimationFrame(animate);
  20. }
  21. else if("webkitRequestAnimationFrame" in window){
  22. webkitRequestAnimationFrame(animate);
  23. }
  24. else if("msRequestAnimationFrame" in window){
  25. msRequestAnimationFrame(animate);
  26. }
  27. else if("mozRequestAnimationFrame" in window){
  28. mozRequestAnimationFrame(animate);
  29. }
  30. else {
  31. setTimeout(animate , 16);
  32. }
  33. }
  34. }

这个就是游戏每一帧的逻辑处理现场,如果小球进洞了,就不再进行绘制,如果辅助虚线的display属性设成false,就不进行辅助虚线的绘制,还有就是计算每一帧的时间。

  【常量与初始化】

  1. var canvas = document.getElementById("cas");
  2. var ctx = canvas.getContext('2d');
  3. var mcl = 1 , collarg = 0.8 , ballRadius = 15 , t0 = 0 , balls=[] , tbw = 32 , animateStop = true , powAnimation = false;
  4. var dotline;
  5. pxpm = canvas.width/20;
  6.  
  7. window.onload = function(){
  8. var myball = new Ball(202 , canvas.height/2 , true);
  9. balls.push(myball);
  10. for(var i=0;i<6;i++){
  11. for(var j=0;j<i;j++){
  12. var other = new Ball(520+i*(ballRadius-2)*2 , (canvas.height-i*2*ballRadius)/2+ballRadius+2*ballRadius*j , false);
  13. balls.push(other);
  14. }
  15. }
  16. t0 = new Date();
  17. dotline = new dotLine(0,0,0,0);
  18.  
  19. animateStop = false;
  20. animate();
  21. }

实例化所有小球,把小球全部按照规律摆好,然后获取当前时间,实例化辅助虚线,动画开始。

源码地址:https://github.com/whxaxes/canvas-test/tree/gh-pages/src/Game-demo/snooker

底部的那两个方法是写两条线相交的判定和交点的获取,想用来写严谨一些的碰撞检测。。。。

好吧,说完了,如果有兴趣的还可以加入声音神马的,我就懒得去做了。。。。。吃饭去咯

用Canvas写桌球游戏!!!的更多相关文章

  1. 尝试用canvas写小游戏

    还是习惯直接开门见山,这个游戏是有一个老师抓作弊的学生,老师背身,点学生开始加分,老师会不定时回头,如果老师回头还在点学生在,就会被抓住,游戏game over. 1.写游戏首先是loading条,于 ...

  2. 用Canvas写一个简单的游戏--别踩白块儿

    第一次写博客也不知怎么写,反正就按照我自己的想法来吧!怎么说呢?还是不要扯那些多余的话了,直接上正题吧! 第一次用canvas写游戏,所以挑个简单实现点的来干:别踩白块儿,其他那些怎么操作的那些就不用 ...

  3. 原生canvas写的飞机游戏

    一个原生canvas写的飞机游戏,实用性不大,主要用于熟悉canvas的一些熟悉用法. 项目地址:https://github.com/BothEyes1993/canvas_game

  4. canvas贪吃蛇游戏

    用canvas做了一个贪吃蛇小游戏 开始界面 游戏界面 结束界面 <!DOCTYPE html>  <html>  <head>  <meta charset ...

  5. 简单的运动学,用canvas写弹力球

    声明:本文为原创文章,如需转载,请注明来源WAxes,谢谢! 跟之前的随笔一样,因为本人仍是菜鸟一只,所以用到的技术比较简单,不适合大神观看...... 学canvas学了有一个多礼拜了,觉得canv ...

  6. 封装构造函数,用canvas写饼状图和柱状图

    封装构造函数,用canvas写饼状图和柱状图 封装函数 // 场景 function XDLScence( options ) { this.stage = options.stage; //执行场景 ...

  7. HTML5 canvas 捕鱼达人游戏

    在线试玩:http://hovertree.com/texiao/html5/33/ html5利用canvas写的一个js版本的捕鱼,有积分统计,鱼可以全方位移动,炮会跟着鼠标移动,第一次打开需要鼠 ...

  8. Javascript写俄罗斯方块游戏

    俄罗斯方块这个游戏也做了移动端的兼容, 这个游戏难点是怎么翻转方块, 自己实现的方式是把方块放到一个二维数组, 然后逆时针旋转二维数组. 也有别的方法,比如直接用一个全局变量代表一个方向, 翻转的时候 ...

  9. 从零开始---控制台用c写俄罗斯方块游戏(1)

    从零开始---控制台用c写俄罗斯方块游戏(1) 很少写博文,一来自身知识有限,二来自己知道,已经有很多这样的博文了,三就是因为懒,文笔也一般,四来刚出来工作,时间也不多 之所以写这篇博文,是因为应群里 ...

随机推荐

  1. Vector3.forward

    这里我要说的就是Vector3.forward ,它等价与 new Vector3(0,0,1):它并不是一个坐标,它是一个标准向量,方向是沿着Z轴向前.这样平移一次的距离就是1米, 如果 Vecto ...

  2. java多线程系类:JUC原子类:05之AtomicIntegerFieldUpdater原子类

    概要 AtomicIntegerFieldUpdater, AtomicLongFieldUpdater和AtomicReferenceFieldUpdater这3个修改类的成员的原子类型的原理和用法 ...

  3. 浅显易懂的理解JavaScript中的this关键字

    在JavaScript中this变量是一个令人难以摸清的关键字,this可谓是非常强大,充分了解this的相关知识有助于我们在编写面向对象的JavaScript程序时能够游刃有余. 1. 一般用处 对 ...

  4. 你一无所知的CSS

    也许标题有点夸大了.虽然不能完全保证大家都不知道这些,但是这也算是一个好机会检测下你是否知道或使用过下面的内容. Selectors Root :root { }  使用root可以让你在DOM中选择 ...

  5. 利用日期、经纬度求日出日落时间 C语言程序代码(zz)

    先贴在这了,后面应该用得着 http://zhidao.baidu.com/link?url=iw-hcd_tLpRtf4r2Kh-NmDPaQ10UdlunBQUWaz14J-eNEq5fw-y83 ...

  6. 吉特仓库管理系统- 斑马打印机 ZPL语言的腐朽和神奇

    上一篇文章说到了.NET中的打印机,在PrintDocument类也暴露一些本质上上的问题,前面也提到过了,虽然使用PrintDcoument打印很方便.对应条码打印机比如斑马等切刀指令,不依赖打印机 ...

  7. 几种xml读取方法比较

    背景 这几天手上有个活,解析xml,众所周知xml的解析方法有: DOM SAX linq to xml plinq 测试用xml和生成代码 static void CreateFile() { ; ...

  8. maven环境配置+eclipse环境配置

    一 . (1),下载maven 有点类似于tomcat 解压后就可以用 ,不用安装 (2), 配置环境变量 在系统变量的path 中添加  E:\01Server\maven\bin    注意是bi ...

  9. 通过CAGradientLayer制作渐变色效果(转)

    转载自:http://blog.it985.com/7986.html 看了极客学院的视频之后写的一篇博客,觉得不错,还是作为笔记使用. 简单介绍一下CAGradientLayer吧. Gradien ...

  10. 【BZOJ-1340】Escape逃跑问题 最小割

    1340: [Baltic2007]Escape逃跑问题 Time Limit: 5 Sec  Memory Limit: 162 MBSubmit: 264  Solved: 121[Submit] ...