Develop html5 2d racing game and package and publish it as a mobile APP Chapter 3 Drag our protagonist's car

Originally I planned to talk directly about how to make NPCs come out automatically, but when I checked the code, I found that making the NPC cars come out involved object-oriented. So I decided to talk about simple object-oriented first, and how to make the protagonist's car be dragged.

 

Then, we have to modify our original code, define a Car class and define the zhujue used to save the instantiated object of the Car class

 

			var zhujue;	
	
			function Car(x,y,width,height,img) {
				this.x=x;
				this.y=y;
				this.width=width;
				this.height=height;
				this.img=img;
                     }

 

 

The properties of the Car class are abscissa x, y coordinate, width width, height height, and img that saves the instantiated object of Image(),

Then instantiate the Car class in the init() method, save it in zhujue, and save the values ​​of the attributes of the protagonist car in the original code in zhujue.x ; zhujue.y ; zhujue.width ; zhujue.height ; zhujue .img

 

 

function init() {
                     .................
                                // instantiate
   				zhujue=Object.create(Car);
                                
                                //
				zhujue.x=canvas1.width / 2 - 40 / 2;
				zhujue.y=canvas1.height - 80;
				zhujue.width=40;
				zhujue.height=80;
                                zhujuepic = new Image();
				zhujue.img=zhujuepic;
                      .................
}

 

 

We also changed the code for drawing the protagonist car and changed it to every attribute of zhujue

 

 

ctx.drawImage(zhujue.img, zhujue.x, zhujue.y, zhujue.width, zhujue.height);

 

 

 

This change, at first glance, is similar to the effect of the previous chapter, but the difference is that every attribute of the protagonist's car is already variable at this time, which is also to prepare for the automatic appearance of NPC vehicles later.

////////////////////////////////////////////////////////////////////////////////////////

 

What we need to do next is to implement the code that the protagonist vehicle can be dragged and moved

The drag and drop function of html5 on mobile devices is inseparable from the following code

 

 

Add the event monitoring processing when the finger is clicked. If it is monitored, it will be processed in the onTouchStart method.
canvas1.addEventListener('touchstart', onTouchStart, false);

Add the event monitoring and processing when the finger is clicked and moved. If it is monitored, it will be processed in the onTouchMove method.
canvas1.addEventListener('touchmove',onTouchMove,false);

Add the event monitoring processing when the finger terminates the dragging. If it is monitored, go to the onTouchEnd method to process it.
canvas1.addEventListener('touchend',onTouchEnd,false);

 

 

 

//Listen to the occurrence of the finger click event, execute the following code
function onTouchStart(event) {
                        .............
			}


//Listen to the occurrence of the finger click and drag event, execute the following code
function onTouchMove(event) {
                        .............
			}

//Listen to the occurrence of the finger termination drag event, execute the following code
function onTouchEnd(event) {
                        ..............	
			}
			

 

So how do you make sure that your finger is on the protagonist car, not the road background? ?

We need to use a code called collision detection function. The so-called collision detection is to detect whether two objects in the game collide; therefore, it is also possible to detect whether the finger collides with the protagonist car.

 

 

	function checkimpact(finger_x, finger_y, el2) {
				var e1 = {
					x: finger_x,
					y: finger_y,
					w: 10,
					h: 10
				}
				var e2 = {
					x: el2.x,
					y: el2.y,
					w: el2.width,
					h: el2.height
				}
				var px, py;
				px = e1.x <= e2.x ? e2.x : e1.x;
				py = e1.y <= e2.y ? e2.y : e1.y;
				if (px >= e1.x && px <= e1.x + e1.w && py >= e1.y && py <= e1.y + e1.h && px >= e2.x && px <= e2.x + e2.w && py >= e2.y && py <= e2.y + e2.h) {

					return true;
				} else {
					return false;
				}
			}

 Explanation: The parameter finger_x is used to transmit the horizontal coordinate under the finger click, the parameter finger_y is used to transmit the vertical coordinate under the finger click, and el2 represents the object to be detected whether it collides with the finger (here is mainly the protagonist car)

var e1 is actually used to save the horizontal and vertical coordinates of the finger click, as well as the width and height of the influence range

var e2 is used to save the horizontal and vertical coordinates of the protagonist car, the width and height of the protagonist car

The whole behind is the collision detection judgment of two objects. The following four judgment processes do not need to be modified. When it returns true, it means that the collision has occurred; when it returns false, it means that the collision did not occur.

 

 

				var px, py;
				px = e1.x <= e2.x ? e2.x : e1.x;
				py = e1.y <= e2.y ? e2.y : e1.y;
				if (px >= e1.x && px <= e1.x + e1.w && py >= e1.y && py <= e1.y + e1.h && px >= e2.x && px <= e2.x + e2.w && py >= e2.y && py <= e2.y + e2.h) {
					return true;
				} else {
					return false;
				}

 

 

 

Then define the global variable is_clicked_zhujue to save the collision detection results between the finger and the protagonist car

 

var is_clicked_zhujue;

 

Then call the checkimpact() method in the method onTouchStart() that handles the event of the finger click to see if the protagonist car is clicked.

 

function onTouchStart(event) {
				//Instantiated object of finger click event
				var touch = event.targetTouches[0];

                                //If the protagonist car is clicked, assign true to is_clicked_zhujue
				if(checkimpact(touch.pageX,touch.pageY,zhujue))
				{
					//alert("1");
				        is_clicked_zhujue=true;
				}
			}

 Explanation: When you see //alert("1"); you may ask what it is and what it is used for. This is the JS bullet box code. If you remove the double slash // comment symbol, combine the entire if(. ......) judgment, that is, when the finger clicks on the protagonist's car, a pop-up box is displayed, the content of the pop-up box is "1" (the pop-up box is commented out in the default code), and then is_clicked_zhujue is assigned to true

 

If HBuilder is used, we copy the current page address of HBuilder's own browser , then open this URL in 360 browser or Google Chrome browser , press F12 on the keyboard to open the debug mode, Device selects the device model to be simulated and debugged ( I randomly chose iPhone5), and then click on the protagonist car to see if a pop-up box is displayed (ordinary web browsers only support mouse clicks and cannot simulate finger clicks, so we must use the simulated mobile phone mode to debug here, otherwise There is no way to debug. Another debugging method is to use HBuilder online to package as an APK installation package, but the efficiency is not good, unless you have implemented a full set of functions, and then put it on your own mobile device to debug)


 

The above picture shows that the protagonist car is clicked, and a pop-up box with the content "1" appears.

 

I want the protagonist's car to move with the finger dragging when the finger is dragged and moved, and implement it in the onTouchMove method.

 

			function onTouchMove(event) {
				//Instantiated object of finger click event
				var touch = event.targetTouches[0];
				
				if(is_clicked_zhujue)
				{
					zhujue.x=touch.pageX-zhujue.width/2;
					zhujue.y=touch.pageY-zhujue.height/2;
				}
			}

Explanation: When the finger is dragged and moved and is_clicked_zhujue is true, assign the abscissa zhujue.x of the protagonist to the X abscissa touch.pageX of the finger event, and assign the vertical coordinate zhujue.y of the protagonist to the Y vertical of the finger event Coordinate touch.pageY, in this way, the protagonist car will follow the finger drag and move

 

 

 

Finally, when the finger click event ends and leaves the screen, it will automatically enter the onTouchEnd() method, so we add the process of assigning the value of is_clicked_zhujue to false to prevent the next wrong drag

 

function onTouchEnd(event) {
				
				
				is_clicked_zhujue=false;
				
			}

 

 Effect



  

full code

 

<!DOCTYPE html>
<html>

	<head>
		<meta charset="utf-8">
		<meta name="viewport" content="initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
		<title>Racing game</title>
		<script type="text/javascript">
			var ctx;
			var canvas1;
			var roadpic;
			var zhujuepic;
			var fenjiepic;
			var fen_y;
			var road_d;
			
			
			var zhujue;
			var is_clicked_zhujue;
			
			function Car(x,y,width,height,img) {
				this.x=x;
				this.y=y;
				this.width=width;
				this.height=height;
				this.img=img;
                     }
			

			function init() {
				
				ctx = document.getElementById('canvas').getContext('2d');
				canvas1 = document.getElementById('canvas');
				
				
				canvas1.addEventListener('touchstart', onTouchStart, false);
				canvas1.addEventListener('touchmove',onTouchMove,false);
				canvas1.addEventListener('touchend',onTouchEnd,false);
				//------------------------------------------//
				zhujue=Object.create(Car);
				zhujue.x=canvas1.width / 2 - 40 / 2;
				zhujue.y=canvas1.height - 80;
				zhujue.width=40;
				zhujue.height=80;
			        zhujuepic = new Image();
				zhujue.img=zhujuepic;
				//------------------------------------------//
				roadpic = new Image();
							
				fenjiepic = new Image();
				roadpic.src = "img/road.png";
				zhujuepic.src = "img/car1.png";
				fenjiepic.src = "img/fenjie.png";
				fen_y = 0;
				road_d = 1;
				setInterval(function(e) {
					animate();
				}, 50);
			}
			
			function onTouchMove(event) {
				
				var touch = event.targetTouches[0];
				
				if(is_clicked_zhujue)
				{
					zhujue.x=touch.pageX-zhujue.width/2;
					zhujue.y=touch.pageY-zhujue.height/2;
				}
			}
			
			function onTouchStart(event) {
				
				var touch = event.targetTouches[0];
				if(checkimpact(touch.pageX,touch.pageY,zhujue))
				{
					//alert("1");
				is_clicked_zhujue=true;
				}
			}
			
			
			function onTouchEnd(event) {
				
				
				is_clicked_zhujue=false;
				
			}

			
			

			function animate() {
				
				ctx.clearRect(0, 0, canvas1.width, canvas1.height);
				//----------------------------------//
				if (road_d == 1) {
					ctx.drawImage(roadpic, 0, 0, canvas1.width + 8, canvas1.height + 8);
					road_d = 0;
				} else {
					ctx.drawImage(roadpic, 0, 0, canvas1.width, canvas1.height);
					road_d = 1;
				}
				
			    //----------------------------------//
				for (var i = 0; i < 50; i++) {
					ctx.drawImage(fenjiepic, canvas1.width / 2 - 10 / 2, fen_y - 80 * i, 10, 30);
				}
				if (fen_y < canvas1.height) {
					fen_y = fen_y + 150;
				} else if (fen_y >= canvas1.height) {
					fen_y = 0;
				}
				
				//----------------------------------//
				ctx.drawImage(zhujue.img, zhujue.x, zhujue.y, zhujue.width, zhujue.height);
			}
			



			function checkimpact(finger_x, finger_y, el2) {
				var e1 = {
					x: finger_x,
					y: finger_y,
					w: 10,
					h: 10
				}
				var e2 = {
					x: el2.x,
					y: el2.y,
					w: el2.width,
					h: el2.height
				}
				var px, py;
				px = e1.x <= e2.x ? e2.x : e1.x;
				py = e1.y <= e2.y ? e2.y : e1.y;
				if (px >= e1.x && px <= e1.x + e1.w && py >= e1.y && py <= e1.y + e1.h && px >= e2.x && px <= e2.x + e2.w && py >= e2.y && py <= e2.y + e2.h) {
					return true;
				} else {
					return false;
				}
			}
		</script>
	</head>

	<body onLoad="init();">
		<canvas id="canvas" width="300" height="540">

		</canvas>
	</body>

</html>

 

 

 

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326418377&siteId=291194637