该游戏教程主要参考了老外Jason Croucher的博客
http://jacebook.co.uk/blog/2010/09/11/html5-writing-a-game/
游戏代码也下载自他的博客。
本教程主要是分析这个游戏的代码,用我自己的语言告诉大家怎么来开发这个游戏
姑且称这个游戏为《蘑菇与熊》吧
游戏的介绍:
用蘑菇顶住熊不给落地,熊碰撞完顶部的奖品为赢。顶部的奖品有3种:叶子、鲜花、橡子
下面开始分析这个游戏解析来该做什么
我使用开发环境是:Dreamweaver
假如没有html5基础的话可以到这里小小补习下
http://www.html5china.com/manual/html5/
假如没有jquery基础的话可以到这里小小补习下
http://www.html5china.com/manual/jquery/
OK~废话少说了,分析游戏
由图我们可以分析出
1、游戏需要到的对象(即游戏物体)有
a、蘑菇 b、熊猫 c、奖品(叶子、鲜花、橡子)
2、html界面
a、画布(用来描绘游戏)
为了简单易懂~我们就不一下子定义完所有的对象和事件了
上回分析了游戏,在这一回我们将让蘑菇跟随鼠标动起来~
达到这个效果:http://www.html5china.com/html5games/mogu/index1.html
一、写html代码
XML/HTML Code复制内容到剪贴板
1. <body>
2. <div id=”container” style=”border:1px solid; cursor:none; width:480px; height:320px;”>
3. <canvas id=”canvas” width=”480″ height=”320″ >
4. </canvas>
5. </div>
6. </body>
用ID为container 的DIV来获取鼠标移动画面的事件
canvas用来绘图
二、定义全局变量
JavaScript Code复制内容到剪贴板
1. //全局变量
2. var backgroundForestImg = new Image();//森林背景图
3. var mushroomImg = new Image();//蘑菇图
4. var ctx;//2d画布
5. var screenWidth;//画布宽度
6. var screenHeight;//画布高度
赋予全局变量值
JavaScript Code复制内容到剪贴板
1. mushroomImg.src = ”images/mushroom.png”;//蘑菇
2. backgroundForestImg.src = ”images/forest1.jpg”;//森林背景图
3. ctx = document.getElementById(‘canvas’).getContext(’2d’);
4. screenWidth = parseInt($(“#canvas”).attr(“width”));
5. screenHeight = parseInt($(“#canvas”).attr(“height”));
三、定义蘑菇实例
由于在画布上的物体全部都有3个共同的属性:x、y坐标,素材image
所以我们定义一个公用的游戏物体
JavaScript Code复制内容到剪贴板
1. //公用 定义一个游戏物体戏对象
2. function GameObject()
3. {
4. this.x = 0;//x 坐标
5. this.y = 0;//y 坐标
6. this.image = null; //图片
7. }
为了方便拓展,定义一个公用的蘑菇
JavaScript Code复制内容到剪贴板
1. //定义公用蘑菇Mushroom 继承游戏对象GameObject
2. function Mushroom() {};
3. Mushroom.prototype = new GameObject();//游戏对象GameObject
定义一个我们使用到的具体蘑菇
JavaScript Code复制内容到剪贴板
1. //蘑菇实例
2. var mushroom = new Mushroom();
初始化蘑菇的位置和图片
JavaScript Code复制内容到剪贴板
1. mushroom.image = mushroomImg;
2. mushroom.x = parseInt(screenWidth/2);
3. mushroom.y = screenHeight - 40;
四、用canvas把蘑菇绘制出来
JavaScript Code复制内容到剪贴板
1. //循环描绘物体
2. function gameLoop()
3. {
4. //清除屏幕
5. ctx.clearRect(0, 0, screenWidth, screenHeight);
6. ctx.save();
7. //绘制背景
8. ctx.drawImage(backgroundForestImg, 0, 0);
9. //绘制蘑菇
10. ctx.drawImage(mushroom.image, mushroom.x, mushroom.y);
11. ctx.restore();
12. }
好了,到这里蘑菇也定义了,背景图也定义了,绘图也定义了,下面就开始整合上面的代码写一个完整的把蘑菇和背景描述在画布上
XML/HTML Code复制内容到剪贴板
1. <!DOCTYPE>
2. <html>
3. <head>
4. <meta http-equiv=”Content-Type” content=”text/html; charset=utf-8″ />
5. <title>蘑菇动起来-html5中文网</title>
6. <!– 要记得引用jquery-1.4.2.js –>
7. <script type=”text/javascript” src=”./js/jquery-1.4.2.js”></script>
8. <script type=”text/javascript” >
9. //全局变量
10. var backgroundForestImg = new Image();//森林背景图
11. var mushroomImg = new Image();//蘑菇
12. var ctx;//2d画布
13. var screenWidth;//画布宽度
14. var screenHeight;//画布高度
15.
16. //公用 定义一个游戏物体戏对象
17. function GameObject()
18. {
19. this.x = 0;
20. this.y = 0;
21. this.image = null;
22. }
23.
24. //定义蘑菇Mushroom 继承游戏对象GameObject
25. function Mushroom() {};
26. Mushroom.prototype = new GameObject();//游戏对象GameObject
27.
28. //蘑菇实例
29. var mushroom = new Mushroom();
1. //循环描绘物体
2. function gameLoop()
3. {
4. //清除屏幕
5. ctx.clearRect(0, 0, screenWidth, screenHeight);
6. ctx.save();
7. //绘制背景
8. ctx.drawImage(backgroundForestImg, 0, 0);
9. //绘制蘑菇
10. ctx.drawImage(mushroom.image, mushroom.x, mushroom.y);
11. ctx.restore();
12. }
13. //加载图片
14. function loadImages()
15. {
16. mushroomImg.src = ”images/mushroom.png”;//蘑菇
17. backgroundForestImg.src = ”images/forest1.jpg”;//森林背景图
18. }
19. //初始化
20. $(window).ready(function(){
21. loadImages();
22. ctx = document.getElementById(‘canvas’).getContext(’2d’); //获取2d画布
23. screenWidth = parseInt($(“#canvas”).attr(“width”)); //画布宽度
24. screenHeight = parseInt($(“#canvas”).attr(“height”));
25. mushroom.image = mushroomImg;
26. mushroom.x = parseInt(screenWidth/2);// 蘑菇X坐标
27. mushroom.y = screenHeight - 40;//蘑菇Y坐标
28. setInterval(gameLoop, 10);
29. });
30.
31.
32. </script>
33. </head>
34.
35. <body>
36. <div id=”container” style=”border:1px solid; cursor:none; width:480px; height:320px;”>
37. <canvas id=”canvas” width=”480″ height=”320″ >
38. </canvas>
39. </div>
40. </body>
41. </html>
蘑菇图片下载地址:http://www.html5china.com/html5games/mogu/images/mushroom.png
背景图片下载地址:http://www.html5china.com/html5games/mogu/images/forest1.jpg
你试着在支持html5的浏览器上运行上面代码试看~是不是蘑菇描绘出来了~
假如你能看到效果了,那祝贺你~你有了个很好的开端~
上面的步骤只是将蘑菇和场景绘出来了,那么接下来我们让他随鼠标动起来~
给DIV#container添加放上鼠标的事件
当鼠标放在DIV#container上面时,蘑菇的X轴坐标等与鼠标的X轴坐标
JavaScript Code复制内容到剪贴板
1. //事件处理
2. function addEventHandlers()
3. {
4. //鼠标移动则蘑菇跟着移动
5. $(“#container”).mousemove(function(e){
6. mushroom.x = e.pageX - (mushroom.image.width/2);
7. });
8.
9. }
我们只要在刚才的演示代码中的 $(window).ready(function(){ }); 里面加上addEventHandlers();就可以了,如下
JavaScript Code复制内容到剪贴板
1. //初始化
2. $(window).ready(function(){
3. addEventHandlers();//加上事件
4. loadImages();
5. ctx = document.getElementById(‘canvas’).getContext(’2d’); //获取2d画布
6. mushroom.image = mushroomImg;
7. screenWidth = parseInt($(“#canvas”).attr(“width”));
8. screenHeight = parseInt($(“#canvas”).attr(“height”));
9. mushroom.x = parseInt(screenWidth/2);
10. mushroom.y = screenHeight - 40;
11. setInterval(gameLoop, 10);
12. });
你再运行代码试下,是不是蘑菇跟着鼠标动起来了~
第二回就讲到这了,第三回讲怎么绘制一只熊并让他滚动起来~ 作者:深邃老马转载自:html5中文网
这一回我们让熊动起来~
预期达到效果:http://www.html5china.com/html5games/mogu/index2.html
一、先定义全局变量
JavaScript Code复制内容到剪贴板
1. var bearEyesClosedImg = new Image();//闭着眼睛的熊熊
2. var horizontalSpeed = 2;//水平速度
3. var verticalSpeed = -2; //垂直速度,开始肯定是要向上飘,所以要负数
4. var bearAngle = 2;//熊旋转的速度
二、定义熊
首先定义一只公用熊
JavaScript Code复制内容到剪贴板
1. //定义动物熊 Animal 继承 游戏对象GameObject
2. function Animal() {};
3. Animal.prototype = new GameObject();//游戏对象GameObject
4. Animal.prototype.angle = 0;//旋转的角度,(用来改变熊的旋转速度)
定义我们使用的熊
JavaScript Code复制内容到剪贴板
1. //定义熊实例
2. var animal = new Animal();
初始化熊
JavaScript Code复制内容到剪贴板
1. bearEyesClosedImg.src = ”images/bear_eyesclosed.png”;//闭着眼睛的
2. animal.image = bearEyesClosedImg;//熊图片
3. animal.x = parseInt(screenWidth/2);//x坐标
4. animal.y = parseInt(screenHeight/2); //y坐标
三、描绘熊在画布上
因为熊是相对移动的,所以我们要加一个基准
JavaScript Code复制内容到剪贴板
1. //以当前熊的中心位置为基准
2. ctx.translate(animal.x + (animal.image.width/2), animal.y + (animal.image.height/2));
3. //描绘熊
4. ctx.drawImage(animal.image, - (animal.image.width/2), - (animal.image.height/2));
但是熊要旋转啊,好的,想要改变它的角度,上面的代码中加入旋转
JavaScript Code复制内容到剪贴板
1. //以当前熊的中心位置为基准
2. ctx.translate(animal.x + (animal.image.width/2), animal.y + (animal.image.height/2));
3. //根据当前熊的角度轮换
4. ctx.rotate(animal.angle * Math.PI/180);
5. //描绘熊
6. ctx.drawImage(animal.image, - (animal.image.width/2), - (animal.image.height/2));
上面的熊是不动的,为什么呢,因为x,y轴和角度没变,因此我们再加上改变x,y和角度的代码,于是上面的代码变成了
JavaScript Code复制内容到剪贴板
1. //改变移动动物X和Y位置
2. animal.x += horizontalSpeed;
3. animal.y += verticalSpeed;
4. //改变翻滚角度
5. animal.angle += bearAngle;
6. //以当前熊的中心位置为基准
7. ctx.translate(animal.x + (animal.image.width/2), animal.y + (animal.image.height/2));
8. //根据当前熊的角度轮换
9. ctx.rotate(animal.angle * Math.PI/180);
10. //描绘熊
11. ctx.drawImage(animal.image, - (animal.image.width/2), - (animal.image.height/2));
到现目前为止熊已经能滚动和移动了,最终代码如下:
折叠展开XML/HTML Code复制内容到剪贴板
1. <!DOCTYPE>
2. <html>
3. <head>
4. <meta http-equiv=”Content-Type” content=”text/html; charset=utf-8″ />
5. <title>蘑菇动起来-html5中文网</title>
6. <!– 要记得引用jquery-1.4.2.js –>
7. <script type=”text/javascript” src=”./js/jquery-1.4.2.js”></script>
8. <script type=”text/javascript” >
9. //全局变量
10. var backgroundForestImg = new Image();//森林背景图
11. var mushroomImg = new Image();//蘑菇
12. var bearEyesClosedImg = new Image();//闭着眼睛的熊熊
13. var ctx;//2d画布
14. var screenWidth;//画布宽度
15. var screenHeight;//画布高度
16. var speed = 2;//不变常量,从新开始的速度
17. var horizontalSpeed = speed;//水平速度,随着熊的碰撞会发生改变
18. var verticalSpeed = -speed; //垂直速度,开始肯定是要向上飘,所以要负数,随着熊的碰撞会发生改变
19. var bearAngle = 2;//熊旋转的速度
20. //公用 定义一个游戏物体戏对象
21. function GameObject()
22. {
23. this.x = 0;
24. this.y = 0;
25. this.image = null;
26. }
27.
28. //定义蘑菇Mushroom 继承游戏对象GameObject
29. function Mushroom() {};
30. Mushroom.prototype = new GameObject();//游戏对象GameObject
31. //蘑菇实例
32. var mushroom = new Mushroom(); //循环描绘物体
33.
34. //定义动物熊 Animal 继承 游戏对象GameObject
35. function Animal() {};
36. Animal.prototype = new GameObject();//游戏对象GameObject
37. Animal.prototype.angle = 0;//动物的角度,目前中(即作为动物它在屏幕上旋转退回)
38. //定义熊实例
39. var animal = new Animal();
40.
41. function GameLoop()
42. {
43. //清除屏幕
44. ctx.clearRect(0, 0, screenWidth, screenHeight);
45. ctx.save();
46. //绘制背景
47. ctx.drawImage(backgroundForestImg, 0, 0);
48. //绘制蘑菇
49. ctx.drawImage(mushroom.image, mushroom.x, mushroom.y);
50. //绘制熊
51. //改变移动动物X和Y位置
52. animal.x += horizontalSpeed;
53. animal.y += verticalSpeed;
54. //改变翻滚角度
55. animal.angle += bearAngle;
56. //以当前熊的中心位置为基准
57. ctx.translate(animal.x + (animal.image.width/2), animal.y + (animal.image.height/2));
58. //根据当前熊的角度轮换
59. ctx.rotate(animal.angle * Math.PI/180);
60. //描绘熊
61. ctx.drawImage(animal.image, - (animal.image.width/2), - (animal.image.height/2));
62. ctx.restore();
63. }
64. //加载图片
65. function LoadImages()
66. {
67. mushroomImg.src = ”images/mushroom.png”;//蘑菇
68. backgroundForestImg.src = ”images/forest1.jpg”;//森林背景图
69. bearEyesClosedImg.src = ”images/bear_eyesclosed.png”;//闭着眼睛的
70.
71. mushroom.image = mushroomImg;
72. animal.image = bearEyesClosedImg;
73. }
74. //事件处理
75. function AddEventHandlers()
76. {
77. //鼠标移动则蘑菇跟着移动
78. $(“#container”).mousemove(function(e){
79. mushroom.x = e.pageX - (mushroom.image.width/2);
80. });
81.
82. }
83. //初始化
84. $(window).ready(function(){
85. AddEventHandlers();//添加事件
86. LoadImages();
87. ctx = document.getElementById(‘canvas’).getContext(’2d’); //获取2d画布
88. screenWidth = parseInt($(“#canvas”).attr(“width”)); //画布宽度
89. screenHeight = parseInt($(“#canvas”).attr(“height”));
90. //初始化蘑菇
91. mushroom.x = parseInt(screenWidth/2);// 蘑菇X坐标
92. mushroom.y = screenHeight - 40;//蘑菇Y坐标
93. //初始化熊
94. animal.x = parseInt(screenWidth/2);
95. animal.y = parseInt(screenHeight/2);
96. setInterval(GameLoop, 10);
97. });
98.
99.
100. </script>
101. </head>
102.
103. <body>
104. <div id=”container” style=”border:1px solid; cursor:none; width:480px; height:320px;”>
105. <canvas id=”canvas” width=”480″ height=”320″ >
106. 浏览器不支持html5,<a target=”_blank” href=”http://www.html5china.com/help/browser.html”>请下载</a>支持html5的浏览器来观看
107. </canvas>
108. </div>
109. </body>
110. </html>
第三回就讲到这了,第四回讲熊碰撞边界和蘑菇的事件 作者:深邃老马转载自:html5中文网
第四回主要讲熊移动碰到边界时的反弹处理
预期达到效果:http://www.html5china.com/html5games/mogu/index3.html
一、写一个碰撞处理函数
JavaScript Code复制内容到剪贴板
1. function HasAnimalHitEdge()
2. {
3. //熊碰到右边边界
4. if(animal.x>screenWidth - animal.image.width)
5. {
6. if(horizontalSpeed > 0)//假如向右移动
7. horizontalSpeed =-horizontalSpeed;//改变水平速度方向
8. }
9. //熊碰到左边边界
10. if(animal.x<-10)
11. {
12. if(horizontalSpeed < 0)//假如向左移动
13. horizontalSpeed = -horizontalSpeed;//改变水平速度方向
14. }
15. //熊碰到下面边界
16. if(animal.y>screenHeight - animal.image.height)
17. {
18. //2秒钟后从新开始
19. setTimeout(function(){
20. horizontalSpeed = speed;
21. verticalSpeed = -speed;
22. animal.x = parseInt(screenWidth/2);
23. animal.y = parseInt(screenHeight/2);
24. gameLoop();
25. }, 2000);
26. }
27. //熊碰到上边边界
28. if(animal.y<0)
29. {
30. verticalSpeed = -verticalSpeed;
31. }
32. }
二、在游戏循环GameLoop()尾部中加入检测边界函数,如下
JavaScript Code复制内容到剪贴板
1. function GameLoop()
2. {
3. //清除屏幕
4. ctx.clearRect(0, 0, screenWidth, screenHeight);
5. ctx.save();
6. //绘制背景
7. ctx.drawImage(backgroundForestImg, 0, 0);
8. //绘制蘑菇
9. ctx.drawImage(mushroom.image, mushroom.x, mushroom.y);
10. //绘制熊
11. //改变移动动物X和Y位置
12. animal.x += horizontalSpeed;
13. animal.y += verticalSpeed;
14. //改变翻滚角度
15. animal.angle += bearAngle;
16. //以当前熊的中心位置为基准
17. ctx.translate(animal.x + (animal.image.width/2), animal.y + (animal.image.height/2));
18. //根据当前熊的角度轮换
19. ctx.rotate(animal.angle * Math.PI/180);
20. //描绘熊
21. ctx.drawImage(animal.image, - (animal.image.width/2), - (animal.image.height/2));
22. ctx.restore();
23. //检测是否碰到边界
24. HasAnimalHitEdge();
25. }
到此第四回的完整代码如下:
折叠展开XML/HTML Code复制内容到剪贴板
1. <!DOCTYPE>
2. <html>
3. <head>
4. <meta http-equiv=”Content-Type” content=”text/html; charset=utf-8″ />
5. <title>蘑菇动起来-html5中文网</title>
6. <!– 要记得引用jquery-1.4.2.js –>
7. <script type=”text/javascript” src=”./js/jquery-1.4.2.js”></script>
8. <script type=”text/javascript” >
9. //全局变量
10. var backgroundForestImg = new Image();//森林背景图
11. var mushroomImg = new Image();//蘑菇
12. var bearEyesClosedImg = new Image();//闭着眼睛的熊熊
13. var ctx;//2d画布
14. var screenWidth;//画布宽度
15. var screenHeight;//画布高度
16. var speed = 2;//不变常量,从新开始的速度
17. var horizontalSpeed = speed;//水平速度,随着熊的碰撞会发生改变
18. var verticalSpeed = -speed; //垂直速度,开始肯定是要向上飘,所以要负数,随着熊的碰撞会发生改变
19. var bearAngle = 2;//熊旋转的速度
20. //公用 定义一个游戏物体戏对象
21. function GameObject()
22. {
23. this.x = 0;
24. this.y = 0;
25. this.image = null;
26. }
27.
28. //定义蘑菇Mushroom 继承游戏对象GameObject
29. function Mushroom() {};
30. Mushroom.prototype = new GameObject();//游戏对象GameObject
31. //蘑菇实例
32. var mushroom = new Mushroom(); //循环描绘物体
33.
34. //定义动物熊 Animal 继承 游戏对象GameObject
35. function Animal() {};
36. Animal.prototype = new GameObject();//游戏对象GameObject
37. Animal.prototype.angle = 0;//动物的角度,目前中(即作为动物它在屏幕上旋转退回)
38. //定义熊实例
39. var animal = new Animal();
40.
41. function GameLoop()
42. {
43. //清除屏幕
44. ctx.clearRect(0, 0, screenWidth, screenHeight);
45. ctx.save();
46. //绘制背景
47. ctx.drawImage(backgroundForestImg, 0, 0);
48. //绘制蘑菇
49. ctx.drawImage(mushroom.image, mushroom.x, mushroom.y);
50. //绘制熊
51. //改变移动动物X和Y位置
52. animal.x += horizontalSpeed;
53. animal.y += verticalSpeed;
54. //改变翻滚角度
55. animal.angle += bearAngle;
56. //以当前熊的中心位置为基准
57. ctx.translate(animal.x + (animal.image.width/2), animal.y + (animal.image.height/2));
58. //根据当前熊的角度轮换
59. ctx.rotate(animal.angle * Math.PI/180);
60. //描绘熊
61. ctx.drawImage(animal.image, - (animal.image.width/2), - (animal.image.height/2));
62. ctx.restore();
63. //检测是否碰到边界
64. HasAnimalHitEdge();
65. }
66. //加载图片
67. function LoadImages()
68. {
69. mushroomImg.src = ”images/mushroom.png”;//蘑菇
70. backgroundForestImg.src = ”images/forest1.jpg”;//森林背景图
71. bearEyesClosedImg.src = ”images/bear_eyesclosed.png”;//闭着眼睛的
72.
73. mushroom.image = mushroomImg;
74. animal.image = bearEyesClosedImg;
75. }
76. function HasAnimalHitEdge()
77. {
78. //熊碰到右边边界
79. if(animal.x>screenWidth - animal.image.width)
80. {
81. if(horizontalSpeed > 0)//假如向右移动
82. horizontalSpeed =-horizontalSpeed;//改变水平速度方向
83. }
84. //熊碰到左边边界
85. if(animal.x<-10)
86. {
87. if(horizontalSpeed < 0)//假如向左移动
88. horizontalSpeed = -horizontalSpeed;//改变水平速度方向
89. }
90. //熊碰到下面边界
91. if(animal.y>screenHeight - animal.image.height)
92. {
93. //2秒钟后从新开始
94. setTimeout(function(){
95. horizontalSpeed = speed;
96. verticalSpeed = -speed;
97. animal.x = parseInt(screenWidth/2);
98. animal.y = parseInt(screenHeight/2);
99. gameLoop();
100. }, 2000);
101. }
102. //熊碰到上边边界
103. if(animal.y<0)
104. {
105. verticalSpeed = -verticalSpeed;
106. }
107. }
108. //事件处理
109. function AddEventHandlers()
110. {
111. //鼠标移动则蘑菇跟着移动
112. $(“#container”).mousemove(function(e){
113. mushroom.x = e.pageX - (mushroom.image.width/2);
114. });
115.
116. }
117. //初始化
118. $(window).ready(function(){
119. AddEventHandlers();//添加事件
120. LoadImages();
121. ctx = document.getElementById(‘canvas’).getContext(’2d’); //获取2d画布
122. screenWidth = parseInt($(“#canvas”).attr(“width”)); //画布宽度
123. screenHeight = parseInt($(“#canvas”).attr(“height”));
124. //初始化蘑菇
125. mushroom.x = parseInt(screenWidth/2);// 蘑菇X坐标
126. mushroom.y = screenHeight - 40;//蘑菇Y坐标
127. //初始化熊
128. animal.x = parseInt(screenWidth/2);
129. animal.y = parseInt(screenHeight/2);
130. setInterval(GameLoop, 10);
131. });
132.
133.
134. </script>
135. </head>
136.
137. <body>
138. <div id=”container” style=”border:1px solid; cursor:none; width:480px; height:320px;”>
139. <canvas id=”canvas” width=”480″ height=”320″ >
140. 浏览器不支持html5,<a target=”_blank” href=”http://www.html5china.com/help/browser.html”>请下载</a>支持html5的浏览器来观看
141. </canvas>
142. </div>
143. </body>
144. </html>
第四回就讲到这了,第五回讲熊碰撞蘑菇的事件作者:深邃老马转载自:html5中文网
第五回主要讲熊碰到蘑菇之后向上反弹的效果
预期达到的效果:http://www.html5china.com/html5games/mogu/index4.html
一、由于碰撞的地方比较多,所以定义一个通用的判断2个物体是否碰撞的函数
JavaScript Code复制内容到剪贴板
1. //方法用途:检测2个物体是否碰撞
2. //参数object1:物体1
3. //参数object1:物体2
4. //参数overlap:可重叠的区域值
5. //返回布尔值:碰撞返回true,不碰撞返回false
6. function CheckIntersect(object1, object2, overlap)
7. {
8. // x-轴 x-轴
9. // A1——>B1 C1 A2——>B2 C2
10. // +——–+ ^ +——–+ ^
11. // | object1| | y-轴 | object2| | y-轴
12. // | | | | | |
13. // +——–+ D1 +——–+ D2
14. // 看图可知两物体各4个点的位置
15. A1 = object1.x + overlap;
16. B1 = object1.x + object1.image.width - overlap;
17. C1 = object1.y + overlap;
18. D1 = object1.y + object1.image.height - overlap;
19.
20. A2 = object2.x + overlap;
21. B2 = object2.x + object2.image.width - overlap;
22. C2 = object2.y + overlap;
23. D2 = object2.y + object2.image.width - overlap;
24.
25. //假如他们在x-轴重叠
26. if(A1 > A2 && A1 < B2
27. || B1 > A2 && B1 < B2)
28. {
29. //判断y-轴重叠
30. if(C1 > C2 && C1 < D1
31. || D1 > C2 && D1 < D2)
32. {
33. //碰撞
34. return true;
35. }
36. }
37. return false;
38. }
二、熊碰撞蘑菇发生的事件以及处理
JavaScript Code复制内容到剪贴板
1. //动物碰撞蘑菇
2. function HasAnimalHitMushroom()
3. {
4. //假如碰撞
5. if(CheckIntersect(animal, mushroom, 5))
6. {
7. //假如碰撞的位置属于蘑菇的左下位置
8. if((animal.x + animal.image.width/2) < (mushroom.x + mushroom.image.width*0.25))
9. {
10. horizontalSpeed = -speed;//反弹
11. }
12. //假如碰撞的位置属于蘑菇的左上位置
13. else if((animal.x + animal.image.width/2) < (mushroom.x + mushroom.image.width*0.5))
14. {
15. //反弹速度减半
16. horizontalSpeed = -speed/2;
17. }
18. //假如碰撞的位置属于蘑菇的右上位置
19. else if((animal.x + animal.image.width/2) < (mushroom.x + mushroom.image.width*0.75))
20. {
21. horizontalSpeed = speed/2;
22. }
23. else
24. {
25. horizontalSpeed = speed;
26. }
27. verticalSpeed = -speed;//改变垂直速度。也即动物向上移动
28.
29. }
30. }
三、在游戏循环GameLoop()尾部中加入熊碰撞蘑菇函数,如下
JavaScript Code复制内容到剪贴板
1. //游戏功能循环
2. function GameLoop()
3. {
4. //清除屏幕
5. ctx.clearRect(0, 0, screenWidth, screenHeight);
6. ctx.save();
7. //绘制背景
8. ctx.drawImage(backgroundForestImg, 0, 0);
9. //绘制蘑菇
10. ctx.drawImage(mushroom.image, mushroom.x, mushroom.y);
11. //绘制熊
12. //改变移动动物X和Y位置
13. animal.x += horizontalSpeed;
14. animal.y += verticalSpeed;
15. //改变翻滚角度
16. animal.angle += bearAngle;
17. //以当前熊的中心位置为基准
18. ctx.translate(animal.x + (animal.image.width/2), animal.y + (animal.image.height/2));
19. //根据当前熊的角度轮换
20. ctx.rotate(animal.angle * Math.PI/180);
21. //描绘熊
22. ctx.drawImage(animal.image, - (animal.image.width/2), - (animal.image.height/2));
23. ctx.restore();
24. //检测是否碰到边界
25. HasAnimalHitEdge();
26. //检测熊碰撞蘑菇
27. HasAnimalHitMushroom();
28. }
到此第五回的完整代码如下:
折叠展开XML/HTML Code复制内容到剪贴板
1. <!DOCTYPE>
2. <html>
3. <head>
4. <meta http-equiv=”Content-Type” content=”text/html; charset=utf-8″ />
5. <title>蘑菇动起来-html5中文网</title>
6. <!– 要记得引用jquery-1.4.2.js –>
7. <script type=”text/javascript” src=”./js/jquery-1.4.2.js”></script>
8. <script type=”text/javascript” >
9. //全局变量
10. var backgroundForestImg = new Image();//森林背景图
11. var mushroomImg = new Image();//蘑菇
12. var bearEyesClosedImg = new Image();//闭着眼睛的熊熊
13. var ctx;//2d画布
14. var screenWidth;//画布宽度
15. var screenHeight;//画布高度
16. var speed = 2;//不变常量,从新开始的速度
17. var horizontalSpeed = speed;//水平速度,随着熊的碰撞会发生改变
18. var verticalSpeed = -speed; //垂直速度,开始肯定是要向上飘,所以要负数,随着熊的碰撞会发生改变
19. var bearAngle = 2;//熊旋转的速度
20. //公用 定义一个游戏物体戏对象
21. function GameObject()
22. {
23. this.x = 0;
24. this.y = 0;
25. this.image = null;
26. }
27.
28. //定义蘑菇Mushroom 继承游戏对象GameObject
29. function Mushroom() {};
30. Mushroom.prototype = new GameObject();//游戏对象GameObject
31. //蘑菇实例
32. var mushroom = new Mushroom(); //循环描绘物体
33.
34. //定义动物熊 Animal 继承 游戏对象GameObject
35. function Animal() {};
36. Animal.prototype = new GameObject();//游戏对象GameObject
37. Animal.prototype.angle = 0;//动物的角度,目前中(即作为动物它在屏幕上旋转退回)
38. //定义熊实例
39. var animal = new Animal();
40. //游戏功能循环
41. function GameLoop()
42. {
43. //清除屏幕
44. ctx.clearRect(0, 0, screenWidth, screenHeight);
45. ctx.save();
46. //绘制背景
47. ctx.drawImage(backgroundForestImg, 0, 0);
48. //绘制蘑菇
49. ctx.drawImage(mushroom.image, mushroom.x, mushroom.y);
50. //绘制熊
51. //改变移动动物X和Y位置
52. animal.x += horizontalSpeed;
53. animal.y += verticalSpeed;
54. //改变翻滚角度
55. animal.angle += bearAngle;
56. //以当前熊的中心位置为基准
57. ctx.translate(animal.x + (animal.image.width/2), animal.y + (animal.image.height/2));
58. //根据当前熊的角度轮换
59. ctx.rotate(animal.angle * Math.PI/180);
60. //描绘熊
61. ctx.drawImage(animal.image, - (animal.image.width/2), - (animal.image.height/2));
62. ctx.restore();
63. //检测是否碰到边界
64. HasAnimalHitEdge();
65. //检测熊碰撞蘑菇
66. HasAnimalHitMushroom();
67. }
68. //加载图片
69. function LoadImages()
70. {
71. mushroomImg.src = ”images/mushroom.png”;//蘑菇
72. backgroundForestImg.src = ”images/forest1.jpg”;//森林背景图
73. bearEyesClosedImg.src = ”images/bear_eyesclosed.png”;//闭着眼睛的
74.
75. mushroom.image = mushroomImg;
76. animal.image = bearEyesClosedImg;
77. }
78. //熊碰撞边界
79. function HasAnimalHitEdge()
80. {
81. //熊碰到右边边界
82. if(animal.x>screenWidth - animal.image.width)
83. {
84. if(horizontalSpeed > 0)//假如向右移动
85. horizontalSpeed =-horizontalSpeed;//改变水平速度方向
86. }
87. //熊碰到左边边界
88. if(animal.x<-10)
89. {
90. if(horizontalSpeed < 0)//假如向左移动
91. horizontalSpeed = -horizontalSpeed;//改变水平速度方向
92. }
93. //熊碰到下面边界
94. if(animal.y>screenHeight - animal.image.height)
95. {
96. //2秒钟后从新开始
97. setTimeout(function(){
98. horizontalSpeed = speed;
99. verticalSpeed = -speed;
100. animal.x = parseInt(screenWidth/2);
101. animal.y = parseInt(screenHeight/2);
102. gameLoop();
103. }, 2000);
104. }
105. //熊碰到上边边界
106. if(animal.y<0)
107. {
108. verticalSpeed = -verticalSpeed;
109. }
110. }
111. //事件处理
112. function AddEventHandlers()
113. {
114. //鼠标移动则蘑菇跟着移动
115. $(“#container”).mousemove(function(e){
116. mushroom.x = e.pageX - (mushroom.image.width/2);
117. });
118.
119. }
120. //方法用途:检测2个物体是否碰撞
121. //参数object1:物体1
122. //参数object1:物体2
123. //参数overlap:可重叠的区域值
124. //返回布尔值:碰撞返回true,不碰撞返回false
125. function CheckIntersect(object1, object2, overlap)
126. {
127. // x-轴 x-轴
128. // A1——>B1 C1 A2——>B2 C2
129. // +——–+ ^ +——–+ ^
130. // | object1| | y-轴 | object2| | y-轴
131. // | | | | | |
132. // +——–+ D1 +——–+ D2
133. // 看图可知两物体各4个点的位置
134. A1 = object1.x + overlap;
135. B1 = object1.x + object1.image.width - overlap;
136. C1 = object1.y + overlap;
137. D1 = object1.y + object1.image.height - overlap;
138.
139. A2 = object2.x + overlap;
140. B2 = object2.x + object2.image.width - overlap;
141. C2 = object2.y + overlap;
142. D2 = object2.y + object2.image.width - overlap;
143.
144. //假如他们在x-轴重叠
145. if(A1 > A2 && A1 < B2
146. || B1 > A2 && B1 < B2)
147. {
148. //判断y-轴重叠
149. if(C1 > C2 && C1 < D1
150. || D1 > C2 && D1 < D2)
151. {
152. //碰撞
153. return true;
154. }
155. }
156. return false;
157. }
158. //动物碰撞蘑菇
159. function HasAnimalHitMushroom()
160. {
161. //假如碰撞
162. if(CheckIntersect(animal, mushroom, 5))
163. {
164. //假如碰撞的位置属于蘑菇的左下位置
165. if((animal.x + animal.image.width/2) < (mushroom.x + mushroom.image.width*0.25))
166. {
167. horizontalSpeed = -speed;//反弹
168. }
169. //假如碰撞的位置属于蘑菇的左上位置
170. else if((animal.x + animal.image.width/2) < (mushroom.x + mushroom.image.width*0.5))
171. {
172. //反弹速度减半
173. horizontalSpeed = -speed/2;
174. }
175. //假如碰撞的位置属于蘑菇的右上位置
176. else if((animal.x + animal.image.width/2) < (mushroom.x + mushroom.image.width*0.75))
177. {
178. horizontalSpeed = speed/2;
179. }
180. else
181. {
182. horizontalSpeed = speed;
183. }
184. verticalSpeed = -speed;//改变垂直速度。也即动物向上移动
185.
186. }
187. }
188. //初始化
189. $(window).ready(function(){
190. AddEventHandlers();//添加事件
191. LoadImages();
192. ctx = document.getElementById(‘canvas’).getContext(’2d’); //获取2d画布
193. screenWidth = parseInt($(“#canvas”).attr(“width”)); //画布宽度
194. screenHeight = parseInt($(“#canvas”).attr(“height”));
195. //初始化蘑菇
196. mushroom.x = parseInt(screenWidth/2);// 蘑菇X坐标
197. mushroom.y = screenHeight - 40;//蘑菇Y坐标
198. //初始化熊
199. animal.x = parseInt(screenWidth/2);
200. animal.y = parseInt(screenHeight/2);
201. setInterval(GameLoop, 10);
202. });
203.
204.
205. </script>
206. </head>
207.
208. <body>
209. <div id=”container” style=”border:1px solid; cursor:none; width:480px; height:320px;”>
210. <canvas id=”canvas” width=”480″ height=”320″ >
211. 浏览器不支持html5,<a target=”_blank” href=”http://www.html5china.com/help/browser.html”>请下载</a>支持html5的浏览器来观看
212. </canvas>
213. </div>
214. </body>
215. </html>
第五回就讲到这了,第六回讲描绘奖品 作者:深邃老马转载自:html5中文网
第五回主要讲怎么把奖品描绘上去
预期达到的效果:http://www.html5china.com/html5games/mogu/index5.html
由于奖品特别多,而且是有序的,所以我们使用一个数组来装所有奖品的位置
一、需要到的全局变量
JavaScript Code复制内容到剪贴板
1. var flowerImg = new Image();//奖品鲜花
2. var leafImg = new Image();//奖品叶子
3. var acornImg = new Image();//奖品橡子
鲜花图片下载:http://www.html5china.com/html5games/mogu/images/flower.png
叶子图片下载:http://www.html5china.com/html5games/mogu/images/leaf.png
橡子图片下载:http://www.html5china.com/html5games/mogu/images/acorn.png
二、初始化托全局变量
JavaScript Code复制内容到剪贴板
1. //加载图片
2. function LoadImages()
3. {
4. mushroomImg.src = ”images/mushroom.png”;//蘑菇
5. backgroundForestImg.src = ”images/forest1.jpg”;//森林背景图
6. bearEyesClosedImg.src = ”images/bear_eyesclosed.png”;//闭着眼睛的
7. flowerImg.src = ”images/flower.png”;//奖品花
8. acornImg.src = ”images/acorn.png”;//奖品橡子
9. leafImg.src = ”images/leaf.png”;//奖品叶子
10.
11. mushroom.image = mushroomImg;
12. animal.image = bearEyesClosedImg;
13. }
三、定义奖品数据及实例
JavaScript Code复制内容到剪贴板
1. //定义奖品数组Prizes和对象Prize,继承游戏对象GameObject
2. var prizes = new Array();
3. function Prize() {};
4. Prize.prototype = new GameObject();//继承游戏对象GameObject
5. Prize.prototype.row = 0;//奖品行位置
6. Prize.prototype.col = 0;//奖品列位置
四、把奖品装进数组
JavaScript Code复制内容到剪贴板
1. //创建奖品数组
2. function InitPrizes()
3. {
4. var count=0;
5. //一共3行
6. for(var x=0; x<3; x++)
7. {
8. //一共23列
9. for(var y=0; y<23; y++)
10. {
11. prize = new Prize();
12. if(x==0)
13. prize.image = flowerImg;//鲜花放在第一行
14. if(x==1)
15. prize.image = acornImg;//豫子刚在第2行
16. if(x==2)
17. prize.image = leafImg;//叶子放在第3行
18.
19. prize.row = x;
20. prize.col = y;
21. prize.x = 20 * prize.col + 10;//x轴位置
22. prize.y = 30 * prize.row + 20;//y轴位置
23. //装入奖品数组,用来描绘
24. prizes[count] = prize;
25. count++;
26. }
27. }
28. }
五、从数组中取出奖品并描绘
JavaScript Code复制内容到剪贴板
1. //绘制奖品,把奖品显示在画布上
2. function DrawPrizes()
3. {
4. for(var x=0; x<prizes.length; x++)
5. {
6. currentPrize = prizes[x];
7. ctx.drawImage(currentPrize.image, prizes[x].x, prizes[x].y);
8. }
9. }
六、在游戏循环GameLoop()中加入描绘奖品的函数,如下
JavaScript Code复制内容到剪贴板
1. function GameLoop()
2. {
3. //清除屏幕
4. ctx.clearRect(0, 0, screenWidth, screenHeight);
5. ctx.save();
6. //绘制背景
7. ctx.drawImage(backgroundForestImg, 0, 0);
8. //绘制蘑菇
9. ctx.drawImage(mushroom.image, mushroom.x, mushroom.y);
10. //绘制奖品
11. DrawPrizes();
12. //绘制熊
13. //改变移动动物X和Y位置
14. animal.x += horizontalSpeed;
15. animal.y += verticalSpeed;
16. //改变翻滚角度
17. animal.angle += bearAngle;
18. //以当前熊的中心位置为基准
19. ctx.translate(animal.x + (animal.image.width/2), animal.y + (animal.image.height/2));
20. //根据当前熊的角度轮换
21. ctx.rotate(animal.angle * Math.PI/180);
22. //描绘熊
23. ctx.drawImage(animal.image, - (animal.image.width/2), - (animal.image.height/2));
24.
25. ctx.restore();
26. //检测是否碰到边界
27. HasAnimalHitEdge();
28. //检测熊碰撞蘑菇
29. HasAnimalHitMushroom();
30.
31. }
到此第六回的完整代码如下:
折叠展开XML/HTML Code复制内容到剪贴板
1. <!DOCTYPE>
2. <html>
3. <head>
4. <meta http-equiv=”Content-Type” content=”text/html; charset=utf-8″ />
5. <title>蘑菇动起来-html5中文网</title>
6. <!– 要记得引用jquery-1.4.2.js –>
7. <script type=”text/javascript” src=”./js/jquery-1.4.2.js”></script>
8. <script type=”text/javascript” >
9. //全局变量
10. var backgroundForestImg = new Image();//森林背景图
11. var mushroomImg = new Image();//蘑菇
12. var bearEyesClosedImg = new Image();//闭着眼睛的熊熊
13. var ctx;//2d画布
14. var screenWidth;//画布宽度
15. var screenHeight;//画布高度
16. var speed = 2;//不变常量,从新开始的速度
17. var horizontalSpeed = speed;//水平速度,随着熊的碰撞会发生改变
18. var verticalSpeed = -speed; //垂直速度,开始肯定是要向上飘,所以要负数,随着熊的碰撞会发生改变
19. var bearAngle = 2;//熊旋转的速度
20. var flowerImg = new Image();//奖品鲜花
21. var leafImg = new Image();//奖品叶子
22. var acornImg = new Image();//奖品橡子
23.
24. //公用 定义一个游戏物体戏对象
25. function GameObject()
26. {
27. this.x = 0;
28. this.y = 0;
29. this.image = null;
30. }
31.
32. //定义蘑菇Mushroom 继承游戏对象GameObject
33. function Mushroom() {};
34. Mushroom.prototype = new GameObject();//游戏对象GameObject
35. //蘑菇实例
36. var mushroom = new Mushroom(); //循环描绘物体
37.
38. //定义动物熊 Animal 继承 游戏对象GameObject
39. function Animal() {};
40. Animal.prototype = new GameObject();//游戏对象GameObject
41. Animal.prototype.angle = 0;//动物的角度,目前中(即作为动物它在屏幕上旋转退回)
42. //定义熊实例
43. var animal = new Animal();
44.
45. //定义奖品数组Prizes和对象Prize,继承游戏对象GameObject
46. var prizes = new Array();
47. function Prize() {};
48. Prize.prototype = new GameObject();//继承游戏对象GameObject
49. Prize.prototype.row = 0;//奖品行位置
50. Prize.prototype.col = 0;//奖品列位置
51.
52. function GameLoop()
53. {
54. //清除屏幕
55. ctx.clearRect(0, 0, screenWidth, screenHeight);
56. ctx.save();
57. //绘制背景
58. ctx.drawImage(backgroundForestImg, 0, 0);
59. //绘制蘑菇
60. ctx.drawImage(mushroom.image, mushroom.x, mushroom.y);
61. //绘制奖品
62. DrawPrizes();
63. //绘制熊
64. //改变移动动物X和Y位置
65. animal.x += horizontalSpeed;
66. animal.y += verticalSpeed;
67. //改变翻滚角度
68. animal.angle += bearAngle;
69. //以当前熊的中心位置为基准
70. ctx.translate(animal.x + (animal.image.width/2), animal.y + (animal.image.height/2));
71. //根据当前熊的角度轮换
72. ctx.rotate(animal.angle * Math.PI/180);
73. //描绘熊
74. ctx.drawImage(animal.image, - (animal.image.width/2), - (animal.image.height/2));
75.
76. ctx.restore();
77. //检测是否碰到边界
78. HasAnimalHitEdge();
79. //检测熊碰撞蘑菇
80. HasAnimalHitMushroom();
81.
82. }
83. //加载图片
84. function LoadImages()
85. {
86. mushroomImg.src = ”images/mushroom.png”;//蘑菇
87. backgroundForestImg.src = ”images/forest1.jpg”;//森林背景图
88. bearEyesClosedImg.src = ”images/bear_eyesclosed.png”;//闭着眼睛的
89. flowerImg.src = ”images/flower.png”;//奖品花
90. acornImg.src = ”images/acorn.png”;//奖品橡子
91. leafImg.src = ”images/leaf.png”;//奖品叶子
92.
93. mushroom.image = mushroomImg;
94. animal.image = bearEyesClosedImg;
95. }
96. //熊碰撞边界
97. function HasAnimalHitEdge()
98. {
99. //熊碰到右边边界
100. if(animal.x>screenWidth - animal.image.width)
101. {
102. if(horizontalSpeed > 0)//假如向右移动
103. horizontalSpeed =-horizontalSpeed;//改变水平速度方向
104. }
105. //熊碰到左边边界
106. if(animal.x<-10)
107. {
108. if(horizontalSpeed < 0)//假如向左移动
109. horizontalSpeed = -horizontalSpeed;//改变水平速度方向
110. }
111. //熊碰到下面边界
112. if(animal.y>screenHeight - animal.image.height)
113. {
114. //2秒钟后从新开始
115. setTimeout(function(){
116. horizontalSpeed = speed;
117. verticalSpeed = -speed;
118. animal.x = parseInt(screenWidth/2);
119. animal.y = parseInt(screenHeight/2);
120. GameLoop();
121. }, 2000);
122. }
123. //熊碰到上边边界
124. if(animal.y<0)
125. {
126. verticalSpeed = -verticalSpeed;
127. }
128. }
129. //事件处理
130. function AddEventHandlers()
131. {
132. //鼠标移动则蘑菇跟着移动
133. $(“#container”).mousemove(function(e){
134. mushroom.x = e.pageX - (mushroom.image.width/2);
135. });
136.
137. }
138. //检测2个物体是否碰撞
139. function CheckIntersect(object1, object2, overlap)
140. {
141. // x-轴 x-轴
142. // A1——>B1 C1 A2——>B2 C2
143. // +——–+ ^ +——–+ ^
144. // | object1| | y-轴 | object2| | y-轴
145. // | | | | | |
146. // +——–+ D1 +——–+ D2
147. //
148. //overlap是重叠的区域值
149. A1 = object1.x + overlap;
150. B1 = object1.x + object1.image.width - overlap;
151. C1 = object1.y + overlap;
152. D1 = object1.y + object1.image.height - overlap;
153.
154. A2 = object2.x + overlap;
155. B2 = object2.x + object2.image.width - overlap;
156. C2 = object2.y + overlap;
157. D2 = object2.y + object2.image.width - overlap;
158.
159. //假如他们在x-轴重叠
160. if(A1 > A2 && A1 < B2
161. || B1 > A2 && B1 < B2)
162. {
163. //判断y-轴重叠
164. if(C1 > C2 && C1 < D1
165. || D1 > C2 && D1 < D2)
166. {
167. //碰撞
168. return true;
169. }
170.
171. }
172. return false;
173. }
174. //动物碰撞蘑菇
175. function HasAnimalHitMushroom()
176. {
177. //假如碰撞
178. if(CheckIntersect(animal, mushroom, 5))
179. {
180. //假如碰撞的位置属于蘑菇的左下位置
181. if((animal.x + animal.image.width/2) < (mushroom.x + mushroom.image.width*0.25))
182. {
183. horizontalSpeed = -speed;//反弹
184. }
185. //假如碰撞的位置属于蘑菇的左上位置
186. else if((animal.x + animal.image.width/2) < (mushroom.x + mushroom.image.width*0.5))
187. {
188. //反弹速度减半
189. horizontalSpeed = -speed/2;
190. }
191. //假如碰撞的位置属于蘑菇的右上位置
192. else if((animal.x + animal.image.width/2) < (mushroom.x + mushroom.image.width*0.75))
193. {
194. horizontalSpeed = speed/2;
195. }
196. else
197. {
198. horizontalSpeed = speed;
199. }
200. verticalSpeed = -speed;//改变垂直速度。也即动物向上移动
201.
202. }
203. }
204. //创建奖品数组
205. function InitPrizes()
206. {
207. var count=0;
208. //一共3行
209. for(var x=0; x<3; x++)
210. {
211. //一共23列
212. for(var y=0; y<23; y++)
213. {
214. prize = new Prize();
215. if(x==0)
216. prize.image = flowerImg;//鲜花放在第一行
217. if(x==1)
218. prize.image = acornImg;//豫子刚在第2行
219. if(x==2)
220. prize.image = leafImg;//叶子放在第3行
221.
222. prize.row = x;
223. prize.col = y;
224. prize.x = 20 * prize.col + 10;//x轴位置
225. prize.y = 30 * prize.row + 20;//y轴位置
226. //装入奖品数组,用来描绘
227. prizes[count] = prize;
228. count++;
229. }
230. }
231. }
232. //绘制奖品,把奖品显示在画布上
233. function DrawPrizes()
234. {
235. for(var x=0; x<prizes.length; x++)
236. {
237. currentPrize = prizes[x];
238. ctx.drawImage(currentPrize.image, prizes[x].x, prizes[x].y);
239. }
240. }
241. //初始化
242. $(window).ready(function(){
243. AddEventHandlers();//添加事件
244. LoadImages();
245. ctx = document.getElementById(‘canvas’).getContext(’2d’); //获取2d画布
246. screenWidth = parseInt($(“#canvas”).attr(“width”)); //画布宽度
247. screenHeight = parseInt($(“#canvas”).attr(“height”));
248. //初始化蘑菇
249. mushroom.x = parseInt(screenWidth/2);// 蘑菇X坐标
250. mushroom.y = screenHeight - 40;//蘑菇Y坐标
251. //初始化熊
252. animal.x = parseInt(screenWidth/2);
253. animal.y = parseInt(screenHeight/2);
254. //初始化奖品
255. InitPrizes();
256. setInterval(GameLoop, 10);
257. });
258.
259.
260. </script>
261. </head>
262.
263. <body>
264. <div id=”container” style=”border:1px solid; cursor:none; width:480px; height:320px;”>
265. <canvas id=”canvas” width=”480″ height=”320″ >
266. 浏览器不支持html5,<a target=”_blank” href=”http://www.html5china.com/help/browser.html”>请下载</a>支持html5的浏览器来观看
267. </canvas>
268. </div>
269. </body>
270. </html>
第六回就讲到这了,第七回讲描绘熊碰到奖品,奖品消失的事件 作者:深邃老马转载自:html5中文网
第七回主要讲熊撞到奖品之后,奖品消失
预期达到的效果:http://www.html5china.com/html5games/mogu/index6.html
简单说下原理:
给奖品加上一个存是否被撞过的属性hit,默认值为false。当奖品撞到的时候。改变hit的值为true。描绘奖品的时候判断hit值是否有没撞到,被撞到的话就不描绘
一、给奖品加hit属性
JavaScript Code复制内容到剪贴板
1. //定义奖品数组Prizes和对象Prize,继承游戏对象GameObject
2. var prizes = new Array();
3. function Prize() {};
4. Prize.prototype = new GameObject();//继承游戏对象GameObject
5. Prize.prototype.row = 0;//奖品行位置
6. Prize.prototype.col = 0;//奖品列位置
7. Prize.prototype.hit = false;//是否被撞过
二、熊撞到奖品事件
JavaScript Code复制内容到剪贴板
1. //撞到奖品
2. function HasAnimalHitPrize()
3. {
4. //取出所有奖品
5. for(var x=0; x<prizes.length; x++)
6. {
7. var prize = prizes[x];
8. //假如没有碰撞过
9. if(!prize.hit)
10. {
11. //判断碰撞
12. if(CheckIntersect(prize, animal, 0))
13. {
14. prize.hit = true;
15. //熊反弹下沉
16. verticalSpeed = speed;
17. }
18. }
19. }
20. }
三、在描绘奖品函数中加如判断是否有被碰撞if(!prize.hit) ,没被撞过,则描绘出来
JavaScript Code复制内容到剪贴板
1. //绘制奖品,把奖品显示在画布上
2. function DrawPrizes()
3. {
4. for(var x=0; x<prizes.length; x++)
5. {
6. currentPrize = prizes[x];
7. //假如没有被撞击,则描绘
8. if(!currentPrize.hit)
9. {
10. ctx.drawImage(currentPrize.image, prizes[x].x, prizes[x].y);
11. }
12. }
13. }
四、在游戏循环GameLoop()尾部中加入检测是否撞到奖品事件函数,如下
1. function GameLoop()
2. {
3. //清除屏幕
4. ctx.clearRect(0, 0, screenWidth, screenHeight);
5. ctx.save();
6. //绘制背景
7. ctx.drawImage(backgroundForestImg, 0, 0);
8. //绘制蘑菇
9. ctx.drawImage(mushroom.image, mushroom.x, mushroom.y);
10. //绘制奖品
11. DrawPrizes();
12. //绘制熊
13. //改变移动动物X和Y位置
14. animal.x += horizontalSpeed;
15. animal.y += verticalSpeed;
16. //改变翻滚角度
17. animal.angle += bearAngle;
18. //以当前熊的中心位置为基准
19. ctx.translate(animal.x + (animal.image.width/2), animal.y + (animal.image.height/2));
20. //根据当前熊的角度轮换
21. ctx.rotate(animal.angle * Math.PI/180);
22. //描绘熊
23. ctx.drawImage(animal.image, - (animal.image.width/2), - (animal.image.height/2));
24. ctx.restore();
25. //检测是否碰到边界
26. HasAnimalHitEdge();
27. //检测熊碰撞蘑菇
28. HasAnimalHitMushroom();
29. //检测熊碰撞奖品
30. HasAnimalHitPrize();
31. }
到此第七回的完整代码如下:
折叠展开XML/HTML Code复制内容到剪贴板
1. <!DOCTYPE>
2. <html>
3. <head>
4. <meta http-equiv=”Content-Type” content=”text/html; charset=utf-8″ />
5. <title>绘制奖品-html5中文网</title>
6. <!– 要记得引用jquery-1.4.2.js –>
7. <script type=”text/javascript” src=”./js/jquery-1.4.2.js”></script>
8. <script type=”text/javascript” >
9. //全局变量
10. var backgroundForestImg = new Image();//森林背景图
11. var mushroomImg = new Image();//蘑菇
12. var bearEyesClosedImg = new Image();//闭着眼睛的熊熊
13. var ctx;//2d画布
14. var screenWidth;//画布宽度
15. var screenHeight;//画布高度
16. var speed = 2;//不变常量,从新开始的速度
17. var horizontalSpeed = speed;//水平速度,随着熊的碰撞会发生改变
18. var verticalSpeed = -speed; //垂直速度,开始肯定是要向上飘,所以要负数,随着熊的碰撞会发生改变
19. var bearAngle = 2;//熊旋转的速度
20. var flowerImg = new Image();//奖品鲜花
21. var leafImg = new Image();//奖品叶子
22. var acornImg = new Image();//奖品橡子
23. //公用 定义一个游戏物体戏对象
24. function GameObject()
25. {
26. this.x = 0;
27. this.y = 0;
28. this.image = null;
29. }
30. //定义蘑菇Mushroom 继承游戏对象GameObject
31. function Mushroom() {};
32. Mushroom.prototype = new GameObject();//游戏对象GameObject
33. //蘑菇实例
34. var mushroom = new Mushroom(); //循环描绘物体
35. //定义动物熊 Animal 继承 游戏对象GameObject
36. function Animal() {};
37. Animal.prototype = new GameObject();//游戏对象GameObject
38. Animal.prototype.angle = 0;//动物的角度,目前中(即作为动物它在屏幕上旋转退回)
39. //定义熊实例
40. var animal = new Animal();
41. //定义奖品数组Prizes和对象Prize,继承游戏对象GameObject
42. var prizes = new Array();
43. function Prize() {};
44. Prize.prototype = new GameObject();//继承游戏对象GameObject
45. Prize.prototype.row = 0;//奖品行位置
46. Prize.prototype.col = 0;//奖品列位置
47. Prize.prototype.hit = false;//是否被撞过
48. function GameLoop()
49. {
50. //清除屏幕
51. ctx.clearRect(0, 0, screenWidth, screenHeight);
52. ctx.save();
53. //绘制背景
54. ctx.drawImage(backgroundForestImg, 0, 0);
55. //绘制蘑菇
56. ctx.drawImage(mushroom.image, mushroom.x, mushroom.y);
57. //绘制奖品
58. DrawPrizes();
59. //绘制熊
60. //改变移动动物X和Y位置
61. animal.x += horizontalSpeed;
62. animal.y += verticalSpeed;
63. //改变翻滚角度
64. animal.angle += bearAngle;
65. //以当前熊的中心位置为基准
66. ctx.translate(animal.x + (animal.image.width/2), animal.y + (animal.image.height/2));
67. //根据当前熊的角度轮换
68. ctx.rotate(animal.angle * Math.PI/180);
69. //描绘熊
70. ctx.drawImage(animal.image, - (animal.image.width/2), - (animal.image.height/2));
71. ctx.restore();
72. //检测是否碰到边界
73. HasAnimalHitEdge();
74. //检测熊碰撞蘑菇
75. HasAnimalHitMushroom();
76. //检测熊碰撞奖品
77. HasAnimalHitPrize();
78. }
79. //加载图片
80. function LoadImages()
81. {
82. mushroomImg.src = ”images/mushroom.png”;//蘑菇
83. backgroundForestImg.src = ”images/forest1.jpg”;//森林背景图
84. bearEyesClosedImg.src = ”images/bear_eyesclosed.png”;//闭着眼睛的
85. flowerImg.src = ”images/flower.png”;//奖品花
86. acornImg.src = ”images/acorn.png”;//奖品橡子
87. leafImg.src = ”images/leaf.png”;//奖品叶子
88. mushroom.image = mushroomImg;
89. animal.image = bearEyesClosedImg;
90. }
91. //熊碰撞边界
92. function HasAnimalHitEdge()
93. {
94. //熊碰到右边边界
95. if(animal.x>screenWidth - animal.image.width)
96. {
97. if(horizontalSpeed > 0)//假如向右移动
98. horizontalSpeed =-horizontalSpeed;//改变水平速度方向
99. }
100. //熊碰到左边边界
101. if(animal.x<-10)
102. {
103. if(horizontalSpeed < 0)//假如向左移动
104. horizontalSpeed = -horizontalSpeed;//改变水平速度方向
105. }
106. //熊碰到下面边界
107. if(animal.y>screenHeight - animal.image.height)
108. {
109. //2秒钟后从新开始
110. setTimeout(function(){
111. horizontalSpeed = speed;
112. verticalSpeed = -speed;
113. animal.x = parseInt(screenWidth/2);
114. animal.y = parseInt(screenHeight/2);
115. GameLoop();
116. }, 2000);
117. }
118. //熊碰到上边边界
119. if(animal.y<0)
120. {
121. verticalSpeed = -verticalSpeed;
122. }
123. }
124. //事件处理
125. function AddEventHandlers()
126. {
127. //鼠标移动则蘑菇跟着移动
128. $(“#container”).mousemove(function(e){
129. mushroom.x = e.pageX - (mushroom.image.width/2);
130. });
131. }
132. //检测2个物体是否碰撞
133. function CheckIntersect(object1, object2, overlap)
134. {
135. // x-轴 x-轴
136. // A1——>B1 C1 A2——>B2 C2
137. // +——–+ ^ +——–+ ^
138. // | object1| | y-轴 | object2| | y-轴
139. // | | | | | |
140. // +——–+ D1 +——–+ D2
141. //
142. //overlap是重叠的区域值
143. A1 = object1.x + overlap;
144. B1 = object1.x + object1.image.width - overlap;
145. C1 = object1.y + overlap;
146. D1 = object1.y + object1.image.height - overlap;
147. A2 = object2.x + overlap;
148. B2 = object2.x + object2.image.width - overlap;
149. C2 = object2.y + overlap;
150. D2 = object2.y + object2.image.width - overlap;
151. //假如他们在x-轴重叠
152. if(A1 > A2 && A1 < B2
153. || B1 > A2 && B1 < B2)
154. {
155. //判断y-轴重叠
156. if(C1 > C2 && C1 < D1
157. || D1 > C2 && D1 < D2)
158. {
159. //碰撞
160. return true;
161. }
162. }
163. return false;
164. }
165. //动物碰撞蘑菇
166. function HasAnimalHitMushroom()
167. {
168. //假如碰撞
169. if(CheckIntersect(animal, mushroom, 5))
170. {
171. //假如碰撞的位置属于蘑菇的左下位置
172. if((animal.x + animal.image.width/2) < (mushroom.x + mushroom.image.width*0.25))
173. {
174. horizontalSpeed = -speed;//反弹
175. }
176. //假如碰撞的位置属于蘑菇的左上位置
177. else if((animal.x + animal.image.width/2) < (mushroom.x + mushroom.image.width*0.5))
178. {
179. //反弹速度减半
180. horizontalSpeed = -speed/2;
181. }
182. //假如碰撞的位置属于蘑菇的右上位置
183. else if((animal.x + animal.image.width/2) < (mushroom.x + mushroom.image.width*0.75))
184. {
185. horizontalSpeed = speed/2;
186. }
187. else
188. {
189. horizontalSpeed = speed;
190. }
191. verticalSpeed = -speed;//改变垂直速度。也即动物向上移动
192. }
193. }
194. //创建奖品数组
195. function InitPrizes()
196. {
197. var count=0;
198. //一共3行
199. for(var x=0; x<3; x++)
200. {
201. //一共23列
202. for(var y=0; y<23; y++)
203. {
204. prize = new Prize();
205. if(x==0)
206. prize.image = flowerImg;//鲜花放在第一行
207. if(x==1)
208. prize.image = acornImg;//豫子刚在第2行
209. if(x==2)
210. prize.image = leafImg;//叶子放在第3行
211. prize.row = x;
212. prize.col = y;
213. prize.x = 20 * prize.col + 10;//x轴位置
214. prize.y = 30 * prize.row + 20;//y轴位置
215. //装入奖品数组,用来描绘
216. prizes[count] = prize;
217. count++;
218. }
219. }
220. }
221. //绘制奖品,把奖品显示在画布上
222. function DrawPrizes()
223. {
224. for(var x=0; x<prizes.length; x++)
225. {
226. currentPrize = prizes[x];
227. //假如没有被撞击,则描绘
228. if(!currentPrize.hit)
229. {
230. ctx.drawImage(currentPrize.image, prizes[x].x, prizes[x].y);
231. }
232. }
233. }
234. //撞到奖品
235. function HasAnimalHitPrize()
236. {
237. //取出所有奖品
238. for(var x=0; x<prizes.length; x++)
239. {
240. var prize = prizes[x];
241. //假如没有碰撞过,则描绘在画布上
242. if(!prize.hit)
243. {
244. //判断碰撞
245. if(CheckIntersect(prize, animal, 0))
246. {
247. prize.hit = true;
248. //熊反弹下沉
249. verticalSpeed = speed;
250. }
251. }
252. }
253. }
254. //初始化
255. $(window).ready(function(){
256. AddEventHandlers();//添加事件
257. LoadImages();
258. ctx = document.getElementById(‘canvas’).getContext(’2d’); //获取2d画布
259. screenWidth = parseInt($(“#canvas”).attr(“width”)); //画布宽度
260. screenHeight = parseInt($(“#canvas”).attr(“height”));
261. //初始化蘑菇
262. mushroom.x = parseInt(screenWidth/2);// 蘑菇X坐标
263. mushroom.y = screenHeight - 40;//蘑菇Y坐标
264. //初始化熊
265. animal.x = parseInt(screenWidth/2);
266. animal.y = parseInt(screenHeight/2);
267. //初始化奖品
268. InitPrizes();
269. setInterval(GameLoop, 10);
270. });
271. </script>
272. </head>
273. <body>
274. <div id=”container” style=”border:1px solid; cursor:none; width:480px; height:320px;”>
275. <canvas id=”canvas” width=”480″ height=”320″ >
276. 浏览器不支持html5,<a target=”_blank” href=”http://www.html5china.com/help/browser.html”>请下载</a>支持html5的浏览器来观看
277. </canvas>
278. </div>
279. </body>
280. </html>
第七回讲完,整个游戏功能的大概框架已经出来了,成功就在眼前~
后面我们的任务就是去完善这个简陋的游戏,比如说加开始按钮、熊的生命数、显示得分、奖品被碰到后旋转再消失、蘑菇被碰到后颤抖几下、音乐等等
讲到这了,相信大家已经对整个游戏的功能、流程差不多了解了。后面的回合就不讲那么详细了,浪费大家的时间是吧~
第八回,开始完善游戏,加开始按钮、生命数、现实得分。作者:深邃老马转载自:html5中文网
第八回合中主要是完善游戏,给游戏加上开始按钮、生命数、得分
预期达到的效果:http://www.html5china.com/html5games/mogu/index7.html
一、添加开始按钮
A、html代码中加入开始按钮,并定位他于画布的中间
XML/HTML Code复制内容到剪贴板
1. <img id=”BtnImgStart” style=”position: absolute; left: 200px; top: 200px; cursor: pointer; float: left; display: block; ” src=”./images/START-Button.png”>
开始图片下载地址:http://www.html5china.com/html5games/mogu/images/START-Button.png
B、全局变量
JavaScript Code复制内容到剪贴板
1. var gameRunning = false;//游戏运行状态
2. var gameloopId;//记住循环的变量
C、原来是游戏自己开始没有暂停的、写一个开始暂停的函数
XML/HTML Code复制内容到剪贴板
1. //开始或者暂停游戏
2. function ToggleGameplay()
3. {
4. gameRunning = !gameRunning;
5. if(gameRunning)
6. {
7. $(“#BtnImgStart”).hide();
8. gameloopId = setInterval(GameLoop, 10);
9. }else
10. {
11. clearInterval(gameloopId);
12. }
13. }
D、添加开始按钮事件
JavaScript Code复制内容到剪贴板
1. //事件处理
2. function AddEventHandlers()
3. {
4. //鼠标移动则蘑菇跟着移动
5. $(“#container”).mousemove(function(e){
6. mushroom.x = e.pageX - (mushroom.image.width/2);
7. });
8. //开始按钮
9. $(“#BtnImgStart”).click(function (){
10. ToggleGameplay();
11. });
12. }
注意,要把$(window).ready(function(){})函数中的setInterval(GameLoop, 10);去掉
二、添加生命数条
A、需要的全局变量
JavaScript Code复制内容到剪贴板
1. var lives=3;//3条生命数
2. var livesImages = new Array();//生命图片数组
B、生命图片初始化
JavaScript Code复制内容到剪贴板
1. //生命图片因为只有6个,所以最多只能6个
2. for(var x=0; x<6; x++)
3. {
4. livesImages[x] = new Image();
5. livesImages[x].src = ”images/lives” + x + ”.png”;
6. }
C、绘制生命条
JavaScript Code复制内容到剪贴板
1. //描绘生命条
2. function DrawLives()
3. {
4. ctx.drawImage(livesImages[lives], 0, 0);
5. }
D、当熊碰到底线时,减一条生命
JavaScript Code复制内容到剪贴板
1. //熊碰到下面边界
2. if(animal.y>screenHeight - animal.image.height)
3. {
4. lives -=1;//生命减1
5. //当还有生命条时,暂停游戏,熊回到中间位置,显出开始按钮
6. if(lives>0)
7. {
8. horizontalSpeed = speed; //初始化水平速度
9. verticalSpeed = -speed; //初始化垂直速度
10. animal.x = parseInt(screenWidth/2); //初始化熊的x坐标
11. animal.y = parseInt(screenHeight/2); //初始化熊的y坐标
12. $(“#BtnImgStart”).show(); //显示开始按钮
13. ToggleGameplay(); //暂停游戏
14. GameLoop(); //初始化绘图
15. }
16. }
E、当生命条数等于0或者奖品消灭完,游戏结束
游戏结束函数
JavaScript Code复制内容到剪贴板
1. //结束游戏
2. function GameOver()
3. {
4. gameRunning = false;
5. clearInterval(gameloopId);
6. alert(“游戏结束!”);
7. }
在熊撞到底线的代码中,加入判断,当生命数=0时,游戏结束
JavaScript Code复制内容到剪贴板
· if(lives<=0)
· GameOver();
在绘制奖品函数中加入判断,当奖品被消灭完时,游戏结束
JavaScript Code复制内容到剪贴板
1. //绘制奖品,把奖品显示在画布上
2. function DrawPrizes()
3. {
4. for(var x=0; x<prizes.length; x++)
5. {
6. currentPrize = prizes[x];
7. //假如没有被撞击,则描绘
8. if(!currentPrize.hit)
9. {
10. ctx.drawImage(currentPrize.image, prizes[x].x, prizes[x].y);
11. }
12. }
13. if(AllPrizesHit())
14. {
15. GameOver();
16. }
17. }
18. //判断是否撞完奖品,假如其中有一个
19. function AllPrizesHit()
20. {
21. for(var c=0; c<prizes.length; c++)
22. {
23. checkPrize = prizes[c];
24. if(checkPrize.hit == false)
25. return false;
26.
27. }
28. return true;
29. }
三、添加得分
A、定义全局变量
JavaScript Code复制内容到剪贴板
1. var score = 0;//分数
2. var scoreImg = new Image();//分数板
B、初始化分数板
JavaScript Code复制内容到剪贴板
1. scoreImg.src = ”images/score.png”;//分数板
C、给奖品加一个分数属性。这样在撞奖品时才能知道得到多少分
JavaScript Code复制内容到剪贴板
1. function Prize() {};
2. Prize.prototype = new GameObject();//继承游戏对象GameObject
3. Prize.prototype.row = 0;//奖品行位置
4. Prize.prototype.col = 0;//奖品列位置
5. Prize.prototype.hit = false;//是否被撞过
6. Prize.prototype.point = 0;//分数
D、在初始化奖品数组中加入分数
JavaScript Code复制内容到剪贴板
1. //创建奖品数组
2. function InitPrizes()
3. {
4. var count=0;
5. //一共3行
6. for(var x=0; x<3; x++)
7. {
8. //一共23列
9. for(var y=0; y<23; y++)
10. {
11. prize = new Prize();
12. if(x==0)
13. {
14. prize.image = flowerImg;//鲜花放在第一行
15. prize.point = 3;//鲜花3分
16. }
17. if(x==1)
18. {
19. prize.image = acornImg;//豫子刚在第2行
20. prize.point = 2;//橡子2分
21. }
22. if(x==2)
23. {
24. prize.image = leafImg;//叶子放在第3行
25. prize.point = 1;//叶子1分
26. }
27.
28. prize.row = x;
29. prize.col = y;
30. prize.x = 20 * prize.col + 10;//x轴位置
31. prize.y = 20 * prize.row + 40;//y轴位置
32. //装入奖品数组,用来描绘
33. prizes[count] = prize;
34. count++;
35. }
36. }
37. }
E、当熊撞到奖品时,根据碰撞奖品的分数增加总分
JavaScript Code复制内容到剪贴板
1. //撞到奖品
2. function HasAnimalHitPrize()
3. {
4. //取出所有奖品
5. for(var x=0; x<prizes.length; x++)
6. {
7. var prize = prizes[x];
8. //假如没有碰撞过
9. if(!prize.hit)
10. {
11. //判断碰撞
12. if(CheckIntersect(prize, animal, 0))
13. {
14. prize.hit = true;
15. //熊反弹下沉
16. verticalSpeed = speed;
17. //总分增加
18. score += prize.point;
19. }
20. }
21. }
22.
23. }
F、绘制分数
JavaScript Code复制内容到剪贴板
1. //描绘分数
2. function DrawScore()
3. {
4. ctx.drawImage(scoreImg, screenWidth-(scoreImg.width),0);//分数板
5. ctx.font = ”12pt Arial”;
6. ctx.fillText(“” + score, 425, 25); //得分
7. }
综合上面的代码, 到此第八回的完整代码如下:
折叠展开XML/HTML Code复制内容到剪贴板
1. <!DOCTYPE>
2. <html>
3. <head>
4. <meta http-equiv=”Content-Type” content=”text/html; charset=utf-8″ />
5. <title>绘制奖品-html5中文网</title>
6. <!– 要记得引用jquery-1.4.2.js –>
7. <script type=”text/javascript” src=”./js/jquery-1.4.2.js”></script>
8. <script type=”text/javascript” >
9. //全局变量
10. var backgroundForestImg = new Image();//森林背景图
11. var mushroomImg = new Image();//蘑菇
12. var bearEyesClosedImg = new Image();//闭着眼睛的熊熊
13. var ctx;//2d画布
14. var screenWidth;//画布宽度
15. var screenHeight;//画布高度
16. var speed = 2;//不变常量,从新开始的速度
17. var horizontalSpeed = speed;//水平速度,随着熊的碰撞会发生改变
18. var verticalSpeed = -speed; //垂直速度,开始肯定是要向上飘,所以要负数,随着熊的碰撞会发生改变
19. var bearAngle = 2;//熊旋转的速度
20. var flowerImg = new Image();//奖品鲜花
21. var leafImg = new Image();//奖品叶子
22. var acornImg = new Image();//奖品橡子
23. var gameRunning = false;//游戏运行状态
24. var gameloopId;//记住循环的变量
25. var lives=3;//3条生命数
26. var livesImages = new Array();//生命图片数组
27. var score = 0;//分数
28. var scoreImg = new Image();//分数板
29. //公用 定义一个游戏物体戏对象
30. function GameObject()
31. {
32. this.x = 0;
33. this.y = 0;
34. this.image = null;
35. }
36.
37. //定义蘑菇Mushroom 继承游戏对象GameObject
38. function Mushroom() {};
39. Mushroom.prototype = new GameObject();//游戏对象GameObject
40. //蘑菇实例
41. var mushroom = new Mushroom(); //循环描绘物体
42.
43. //定义动物熊 Animal 继承 游戏对象GameObject
44. function Animal() {};
45. Animal.prototype = new GameObject();//游戏对象GameObject
46. Animal.prototype.angle = 0;//动物的角度,目前中(即作为动物它在屏幕上旋转退回)
47. //定义熊实例
48. var animal = new Animal();
49.
50. //定义奖品数组Prizes和对象Prize,继承游戏对象GameObject
51. var prizes = new Array();
52. function Prize() {};
53. Prize.prototype = new GameObject();//继承游戏对象GameObject
54. Prize.prototype.row = 0;//奖品行位置
55. Prize.prototype.col = 0;//奖品列位置
56. Prize.prototype.hit = false;//是否被撞过
57. Prize.prototype.point = 0;//分数
58.
59. function GameLoop()
60. {
61. //清除屏幕
62. ctx.clearRect(0, 0, screenWidth, screenHeight);
63. ctx.save();
64. //绘制背景
65. ctx.drawImage(backgroundForestImg, 0, 0);
66. //绘制蘑菇
67. ctx.drawImage(mushroom.image, mushroom.x, mushroom.y);
68. //绘制奖品
69. DrawPrizes();
70. //绘制生命条
71. DrawLives();
72. //绘制分数板
73. DrawScore();
74. //绘制熊
75. //改变移动动物X和Y位置
76. animal.x += horizontalSpeed;
77. animal.y += verticalSpeed;
78. //改变翻滚角度
79. animal.angle += bearAngle;
80. //以当前熊的中心位置为基准
81. ctx.translate(animal.x + (animal.image.width/2), animal.y + (animal.image.height/2));
82. //根据当前熊的角度轮换
83. ctx.rotate(animal.angle * Math.PI/180);
84. //描绘熊
85. ctx.drawImage(animal.image, - (animal.image.width/2), - (animal.image.height/2));
86.
87. ctx.restore();
88. //检测是否碰到边界
89. HasAnimalHitEdge();
90. //检测熊碰撞蘑菇
91. HasAnimalHitMushroom();
92. //检测熊碰撞奖品
93. HasAnimalHitPrize();
94. }
95. //加载图片
96. function LoadImages()
97. {
98. mushroomImg.src = ”images/mushroom.png”;//蘑菇
99. backgroundForestImg.src = ”images/forest1.jpg”;//森林背景图
100. bearEyesClosedImg.src = ”images/bear_eyesclosed.png”;//闭着眼睛的
101. flowerImg.src = ”images/flower.png”;//奖品花
102. acornImg.src = ”images/acorn.png”;//奖品橡子
103. leafImg.src = ”images/leaf.png”;//奖品叶子
104. scoreImg.src = ”images/score.png”;//分数板
105. //生命图片因为只有6个,所以最多只能6个
106. for(var x=0; x<6; x++)
107. {
108. livesImages[x] = new Image();
109. livesImages[x].src = ”images/lives” + x + ”.png”;
110. }
111.
112. mushroom.image = mushroomImg;
113. animal.image = bearEyesClosedImg;
114. backgroundForestImg.onload = function(){GameLoop(); };
115. }
116. //熊碰撞边界
117. function HasAnimalHitEdge()
118. {
119. //熊碰到右边边界
120. if(animal.x>screenWidth - animal.image.width)
121. {
122. if(horizontalSpeed > 0)//假如向右移动
123. horizontalSpeed =-horizontalSpeed;//改变水平速度方向
124. }
125. //熊碰到左边边界
126. if(animal.x<-10)
127. {
128. if(horizontalSpeed < 0)//假如向左移动
129. horizontalSpeed = -horizontalSpeed;//改变水平速度方向
130. }
131. //熊碰到下面边界
132. if(animal.y>screenHeight - animal.image.height)
133. {
134. lives -=1;//生命减1
135. if(lives>0)
136. {
137. horizontalSpeed = speed;
138. verticalSpeed = -speed;
139. animal.x = parseInt(screenWidth/2);
140. animal.y = parseInt(screenHeight/2);
141. $(“#BtnImgStart”).show();
142. ToggleGameplay();
143. GameLoop();
144. }
145. }
146. //熊碰到上边边界
147. if(animal.y<0)
148. {
149. verticalSpeed = -verticalSpeed;
150. }
151. if(lives<=0)
152. GameOver();
153. }
154. //事件处理
155. function AddEventHandlers()
156. {
157. //鼠标移动则蘑菇跟着移动
158. $(“#container”).mousemove(function(e){
159. mushroom.x = e.pageX - (mushroom.image.width/2);
160. });
161. //开始按钮
162. $(“#BtnImgStart”).click(function (){
163. ToggleGameplay();
164. });
165. }
166. //检测2个物体是否碰撞
167. function CheckIntersect(object1, object2, overlap)
168. {
169. // x-轴 x-轴
170. // A1——>B1 C1 A2——>B2 C2
171. // +——–+ ^ +——–+ ^
172. // | object1| | y-轴 | object2| | y-轴
173. // | | | | | |
174. // +——–+ D1 +——–+ D2
175. //
176. //overlap是重叠的区域值
177. A1 = object1.x + overlap;
178. B1 = object1.x + object1.image.width - overlap;
179. C1 = object1.y + overlap;
180. D1 = object1.y + object1.image.height - overlap;
181.
182. A2 = object2.x + overlap;
183. B2 = object2.x + object2.image.width - overlap;
184. C2 = object2.y + overlap;
185. D2 = object2.y + object2.image.width - overlap;
186.
187. //假如他们在x-轴重叠
188. if(A1 > A2 && A1 < B2
189. || B1 > A2 && B1 < B2)
190. {
191. //判断y-轴重叠
192. if(C1 > C2 && C1 < D1
193. || D1 > C2 && D1 < D2)
194. {
195. //碰撞
196. return true;
197. }
198.
199. }
200. return false;
201. }
202. //动物碰撞蘑菇
203. function HasAnimalHitMushroom()
204. {
205. //假如碰撞
206. if(CheckIntersect(animal, mushroom, 5))
207. {
208. //假如碰撞的位置属于蘑菇的左下位置
209. if((animal.x + animal.image.width/2) < (mushroom.x + mushroom.image.width*0.25))
210. {
211. horizontalSpeed = -speed;//反弹
212. }
213. //假如碰撞的位置属于蘑菇的左上位置
214. else if((animal.x + animal.image.width/2) < (mushroom.x + mushroom.image.width*0.5))
215. {
216. //反弹速度减半
217. horizontalSpeed = -speed/2;
218. }
219. //假如碰撞的位置属于蘑菇的右上位置
220. else if((animal.x + animal.image.width/2) < (mushroom.x + mushroom.image.width*0.75))
221. {
222. horizontalSpeed = speed/2;
223. }
224. else
225. {
226. horizontalSpeed = speed;
227. }
228. verticalSpeed = -speed;//改变垂直速度。也即动物向上移动
229.
230. }
231. }
232. //创建奖品数组
233. function InitPrizes()
234. {
235. var count=0;
236. //一共3行
237. for(var x=0; x<3; x++)
238. {
239. //一共23列
240. for(var y=0; y<23; y++)
241. {
242. prize = new Prize();
243. if(x==0)
244. {
245. prize.image = flowerImg;//鲜花放在第一行
246. prize.point = 3;//3分
247. }
248. if(x==1)
249. {
250. prize.image = acornImg;//豫子刚在第2行
251. prize.point = 2;//2分
252. }
253. if(x==2)
254. {
255. prize.image = leafImg;//叶子放在第3行
256. prize.point = 1;//1分
257. }
258.
259. prize.row = x;
260. prize.col = y;
261. prize.x = 20 * prize.col + 10;//x轴位置
262. prize.y = 20 * prize.row + 40;//y轴位置
263. //装入奖品数组,用来描绘
264. prizes[count] = prize;
265. count++;
266. }
267. }
268. }
269. //绘制奖品,把奖品显示在画布上
270. function DrawPrizes()
271. {
272. for(var x=0; x<prizes.length; x++)
273. {
274. currentPrize = prizes[x];
275. //假如没有被撞击,则描绘
276. if(!currentPrize.hit)
277. {
278. ctx.drawImage(currentPrize.image, prizes[x].x, prizes[x].y);
279. }
280. }
281. if(AllPrizesHit())
282. {
283. GameOver();
284. }
285. }
286.
287. //撞到奖品
288. function HasAnimalHitPrize()
289. {
290. //取出所有奖品
291. for(var x=0; x<prizes.length; x++)
292. {
293. var prize = prizes[x];
294. //假如没有碰撞过
295. if(!prize.hit)
296. {
297. //判断碰撞
298. if(CheckIntersect(prize, animal, 0))
299. {
300. prize.hit = true;
301. //熊反弹下沉
302. verticalSpeed = speed;
303. //总分增加
304. score += prize.point;
305. }
306. }
307. }
308.
309. }
310. //判断是否撞完奖品,假如其中有一个
311. function AllPrizesHit()
312. {
313. for(var c=0; c<prizes.length; c++)
314. {
315. checkPrize = prizes[c];
316. if(checkPrize.hit == false)
317. return false;
318.
319. }
320. return true;
321. }
322. //开始或者暂停游戏
323. function ToggleGameplay()
324. {
325. gameRunning = !gameRunning;
326. if(gameRunning)
327. {
328. $(“#BtnImgStart”).hide();
329. gameloopId = setInterval(GameLoop, 10);
330. }else
331. {
332. clearInterval(gameloopId);
333. }
334. }
335. //结束游戏
336. function GameOver()
337. {
338. gameRunning = false;
339. clearInterval(gameloopId);
340. alert(“游戏结束!”);
341. }
342. //描绘生命条
343. function DrawLives()
344. {
345. ctx.drawImage(livesImages[lives], 0, 0);
346. }
347. //描绘分数
348. function DrawScore()
349. {
350. ctx.drawImage(scoreImg, screenWidth-(scoreImg.width),0);//分数板
351. ctx.font = ”12pt Arial”;
352. ctx.fillText(“” + score, 425, 25); //得分
353. }
354. //初始化
355. $(window).ready(function(){
356. AddEventHandlers();//添加事件
357. LoadImages();
358. ctx = document.getElementById(‘canvas’).getContext(’2d’); //获取2d画布
359. screenWidth = parseInt($(“#canvas”).attr(“width”)); //画布宽度
360. screenHeight = parseInt($(“#canvas”).attr(“height”));
361. //初始化蘑菇
362. mushroom.x = parseInt(screenWidth/2);// 蘑菇X坐标
363. mushroom.y = screenHeight - 40;//蘑菇Y坐标
364. //初始化熊
365. animal.x = parseInt(screenWidth/2);
366. animal.y = parseInt(screenHeight/2);
367. //初始化奖品
368. InitPrizes();
369.
370. });
371.
372.
373. </script>
374. </head>
375.
376. <body>
377. <div id=”container” style=”border:1px solid; cursor:none; width:480px; height:320px;”>
378. <canvas id=”canvas” width=”480″ height=”320″ >
379. 浏览器不支持html5,<a target=”_blank” href=”http://www.html5china.com/help/browser.html”>请下载</a>支持html5的浏览器来观看
380. </canvas>
381. </div>
382. <img id=”BtnImgStart” style=”position: absolute; left: 200px; top: 200px; cursor: pointer; float: left; display: block; ” src=”./images/START-Button.png”>
383. </body>
384. </html>
第八回讲完,整个游戏功能的基本已经做出来了。
到这里教程先告一段落先。
其实整个游戏其实还可以继续完善,比如说蘑菇被碰到后颤抖几下、碰撞声音、加入游戏帧数、加入关数、不同的关数、不同的动物和奖品、难度。。等等
假如后面有空的话我再继续完善这个游戏。作者:深邃老马转载自:html5中文网
所以有代码
<!DOCTYPE>
<html>
<head>
<meta http-equiv="Content-Type"content="text/html; charset=utf-8" />
<title>绘制奖品-html5中文网</title>
<!-- 要记得引用jquery-1.4.2.js -->
<script type="text/javascript"src="./js/jquery-1.4.2.js"></script>
<script type="text/javascript">
//全局变量
varbackgroundForestImg = new Image();//森林背景图
varmushroomImg = new Image();//蘑菇
varbearEyesClosedImg = new Image();//闭着眼睛的熊熊
varctx;//2d画布
varscreenWidth;//画布宽度
varscreenHeight;//画布高度
varspeed = 2;//不变常量,从新开始的速度
varhorizontalSpeed = speed;//水平速度,随着熊的碰撞会发生改变
varverticalSpeed = -speed; //垂直速度,开始肯定是要向上飘,所以要负数,随着熊的碰撞会发生改变
varbearAngle = 2;//熊旋转的速度
varflowerImg = new Image();//奖品鲜花
varleafImg = new Image();//奖品叶子
varacornImg = new Image();//奖品橡子
vargameRunning = false;//游戏运行状态
vargameloopId;//记住循环的变量
varlives=3;//3条生命数
varlivesImages = new Array();//生命图片数组
varscore = 0;//分数
varscoreImg = new Image();//分数板
//公用 定义一个游戏物体戏对象
function GameObject()
{
this.x = 0;
this.y = 0;
this.image = null;
}
//定义蘑菇Mushroom 继承游戏对象GameObject
function Mushroom() {};
Mushroom.prototype = new GameObject();//游戏对象GameObject
//蘑菇实例
varmushroom = new Mushroom(); //循环描绘物体
//定义动物熊 Animal 继承 游戏对象GameObject
functionAnimal() {};
Animal.prototype= new GameObject();//游戏对象GameObject
Animal.prototype.angle= 0;//动物的角度,目前中(即作为动物它在屏幕上旋转退回)
//定义熊实例
varanimal = new Animal();
//定义奖品数组Prizes和对象Prize,继承游戏对象GameObject
varprizes = new Array();
functionPrize() {};
Prize.prototype= new GameObject();//继承游戏对象GameObject
Prize.prototype.row= 0;//奖品行位置
Prize.prototype.col= 0;//奖品列位置
Prize.prototype.hit= false;//是否被撞过
Prize.prototype.point= 0;//分数
function GameLoop()
{
//清除屏幕
ctx.clearRect(0, 0, screenWidth, screenHeight);
ctx.save();
//绘制背景
ctx.drawImage(backgroundForestImg, 0, 0);
//绘制蘑菇
ctx.drawImage(mushroom.image, mushroom.x, mushroom.y);
//绘制奖品
DrawPrizes();
//绘制生命条
DrawLives();
//绘制分数板
DrawScore();
//绘制熊
//改变移动动物X和Y位置
animal.x+= horizontalSpeed;
animal.y+= verticalSpeed;
//改变翻滚角度
animal.angle+= bearAngle;
//以当前熊的中心位置为基准
ctx.translate(animal.x +(animal.image.width/2), animal.y + (animal.image.height/2));
//根据当前熊的角度轮换
ctx.rotate(animal.angle * Math.PI/180);
//描绘熊
ctx.drawImage(animal.image,- (animal.image.width/2), - (animal.image.height/2));
ctx.restore();
//检测是否碰到边界
HasAnimalHitEdge();
//检测熊碰撞蘑菇
HasAnimalHitMushroom();
//检测熊碰撞奖品
HasAnimalHitPrize();
}
//加载图片
function LoadImages()
{
mushroomImg.src = "images/mushroom.png";//蘑菇
backgroundForestImg.src = "images/forest1.jpg";//森林背景图
bearEyesClosedImg.src= "images/bear_eyesclosed.png";//闭着眼睛的
flowerImg.src= "images/flower.png";//奖品花
acornImg.src= "images/acorn.png";//奖品橡子
leafImg.src= "images/leaf.png";//奖品叶子
scoreImg.src= "images/score.png";//分数板
//生命图片因为只有6个,所以最多只能6个
for(varx=0; x<6; x++)
{
livesImages[x]= new Image();
livesImages[x].src= "images/lives" + x + ".png";
}
mushroom.image= mushroomImg;
animal.image= bearEyesClosedImg;
backgroundForestImg.οnlοad= function(){GameLoop(); };
}
//熊碰撞边界
functionHasAnimalHitEdge()
{
//熊碰到右边边界
if(animal.x>screenWidth- animal.image.width)
{
if(horizontalSpeed > 0)//假如向右移动
horizontalSpeed=-horizontalSpeed;//改变水平速度方向
}
//熊碰到左边边界
if(animal.x<-10)
{
if(horizontalSpeed< 0)//假如向左移动
horizontalSpeed= -horizontalSpeed;//改变水平速度方向
}
//熊碰到下面边界
if(animal.y>screenHeight- animal.image.height)
{
lives-=1;//生命减1
if(lives>0)
{
horizontalSpeed= speed;
verticalSpeed= -speed;
animal.x= parseInt(screenWidth/2);
animal.y= parseInt(screenHeight/2);
$("#BtnImgStart").show();
ToggleGameplay();
GameLoop();
}
}
//熊碰到上边边界
if(animal.y<0)
{
verticalSpeed= -verticalSpeed;
}
if(lives<=0)
GameOver();
}
//事件处理
functionAddEventHandlers()
{
//鼠标移动则蘑菇跟着移动
$("#container").mousemove(function(e){
mushroom.x= e.pageX - (mushroom.image.width/2);
});
//开始按钮
$("#BtnImgStart").click(function(){
ToggleGameplay();
});
}
//检测2个物体是否碰撞
functionCheckIntersect(object1, object2, overlap)
{
// x-轴 x-轴
// A1------>B1 C1 A2------>B2 C2
// +--------+ ^ +--------+ ^
// | object1| | y-轴 | object2| | y-轴
// | | | | | |
// +--------+ D1 +--------+ D2
//
//overlap是重叠的区域值
A1= object1.x + overlap;
B1= object1.x + object1.image.width - overlap;
C1= object1.y + overlap;
D1= object1.y + object1.image.height - overlap;
A2= object2.x + overlap;
B2= object2.x + object2.image.width - overlap;
C2= object2.y + overlap;
D2= object2.y + object2.image.width - overlap;
//假如他们在x-轴重叠
if(A1> A2 && A1 < B2
|| B1 > A2 && B1 < B2)
{
//判断y-轴重叠
if(C1> C2 && C1 < D1
|| D1 > C2 && D1 < D2)
{
//碰撞
returntrue;
}
}
returnfalse;
}
//动物碰撞蘑菇
functionHasAnimalHitMushroom()
{
//假如碰撞
if(CheckIntersect(animal,mushroom, 5))
{
//假如碰撞的位置属于蘑菇的左下位置
if((animal.x+ animal.image.width/2) < (mushroom.x + mushroom.image.width*0.25))
{
horizontalSpeed= -speed;//反弹
}
//假如碰撞的位置属于蘑菇的左上位置
elseif((animal.x + animal.image.width/2) < (mushroom.x +mushroom.image.width*0.5))
{
//反弹速度减半
horizontalSpeed= -speed/2;
}
//假如碰撞的位置属于蘑菇的右上位置
elseif((animal.x + animal.image.width/2) < (mushroom.x +mushroom.image.width*0.75))
{
horizontalSpeed= speed/2;
}
else
{
horizontalSpeed= speed;
}
verticalSpeed= -speed;//改变垂直速度。也即动物向上移动
}
}
//创建奖品数组
functionInitPrizes()
{
varcount=0;
//一共3行
for(varx=0; x<3; x++)
{
//一共23列
for(vary=0; y<23; y++)
{
prize= new Prize();
if(x==0)
{
prize.image= flowerImg;//鲜花放在第一行
prize.point= 3;//3分
}
if(x==1)
{
prize.image= acornImg;//豫子刚在第2行
prize.point= 2;//2分
}
if(x==2)
{
prize.image= leafImg;//叶子放在第3行
prize.point= 1;//1分
}
prize.row= x;
prize.col= y;
prize.x= 20 * prize.col + 10;//x轴位置
prize.y= 20 * prize.row + 40;//y轴位置
//装入奖品数组,用来描绘
prizes[count]= prize;
count++;
}
}
}
//绘制奖品,把奖品显示在画布上
functionDrawPrizes()
{
for(varx=0; x<prizes.length; x++)
{
currentPrize= prizes[x];
//假如没有被撞击,则描绘
if(!currentPrize.hit)
{
ctx.drawImage(currentPrize.image,prizes[x].x, prizes[x].y);
}
}
if(AllPrizesHit())
{
GameOver();
}
}
//撞到奖品
functionHasAnimalHitPrize()
{
//取出所有奖品
for(varx=0; x<prizes.length; x++)
{
varprize = prizes[x];
//假如没有碰撞过
if(!prize.hit)
{
//判断碰撞
if(CheckIntersect(prize,animal, 0))
{
prize.hit= true;
//熊反弹下沉
verticalSpeed= speed;
//得分
score+= prize.point;
}
}
}
}
//判断是否撞完奖品,假如其中有一个
functionAllPrizesHit()
{
for(varc=0; c<prizes.length; c++)
{
checkPrize= prizes[c];
if(checkPrize.hit== false)
returnfalse;
}
returntrue;
}
//开始或者暂停游戏
functionToggleGameplay()
{
gameRunning= !gameRunning;
if(gameRunning)
{
$("#BtnImgStart").hide();
gameloopId = setInterval(GameLoop, 10);
}else
{
clearInterval(gameloopId);
}
}
//结束游戏
functionGameOver()
{
gameRunning= false;
clearInterval(gameloopId);
alert("游戏结束!");
}
//描绘生命条
functionDrawLives()
{
ctx.drawImage(livesImages[lives],0, 0);
}
//描绘分数
functionDrawScore()
{
ctx.drawImage(scoreImg,screenWidth-(scoreImg.width),0);
ctx.font= "12ptArial";
ctx.fillText("" + score, 425, 25);
}
//初始化
$(window).ready(function(){
AddEventHandlers();//添加事件
LoadImages();
ctx = document.getElementById('canvas').getContext('2d'); //获取2d画布
screenWidth = parseInt($("#canvas").attr("width")); //画布宽度
screenHeight = parseInt($("#canvas").attr("height"));
//初始化蘑菇
mushroom.x = parseInt(screenWidth/2);// 蘑菇X坐标
mushroom.y = screenHeight - 40;//蘑菇Y坐标
//初始化熊
animal.x= parseInt(screenWidth/2);
animal.y= parseInt(screenHeight/2);
//初始化奖品
InitPrizes();
});
</script>
</head>
<body>
<div id="container" style="border:1px solid; cursor:none;width:480px; height:320px;">
<canvas id="canvas" width="480" height="320" >
浏览器不支持html5,<a target="_blank" href="http://www.html5china.com/help/browser.html">请下载</a>支持html5的浏览器来观看
</canvas>
</div>
<img id="BtnImgStart" style="position: absolute; left: 200px;top: 200px; cursor: pointer; float: left; display: block; " src="./images/START-Button.png">
<div class="Copyrights">
<br />
<a href="http://www.html5china.com">由HTML5中文网整理收集,更多精彩请关注 www.HTML5China.com </a> <br />
<script src="http://s15.cnzz.com/stat.php?id=2297124&web_id=2297124" language="JavaScript"></script></div>
</body>
</html>