Home > Web Front-end > JS Tutorial > Implement the method of determining collision through JS!

Implement the method of determining collision through JS!

jacklove
Release: 2018-06-15 15:52:59
Original
1800 people have browsed it

This time I will give you an example of how to use JS to determine collisions. There are many application scenarios for collision, such as setting off fireworks, small balls bouncing off walls, pixel birds, etc., so we must first figure out how to determine collision before we can proceed with future operations.

HTML page code:

<p id="d1"></p>
<p id="d2"></p>
Copy after login

CSS page code:

<style type="text/css">
		*{
			padding: 0px;
			margin: 0px;

		}
		#d1{
			width: 100px;
			height: 100px;
			background: red;
			position: absolute;
		}
		#d2{
			width: 200px;
			height: 200px;
			background: yellow;
			position: absolute;
			top: 200px;
			left: 400px;
			position: absolute;
		}
	</style>
Copy after login

JS page code:

<script type="text/javascript">
	p=document.querySelectorAll("p"); 
function hit(obj){
	obj.onmousedown=function(e){
		var e=e||window.event;
		var dX=e.offsetX;
		var dY=e.offsetY;
		document.onmousemove=function(e){
			var x=e.clientX;
			var y=e.clientY;
			obj.style.left=x-dX+"px";
			obj.style.top=y-dY+"px";
			if(p[0].offsetTop+p[0].offsetHeight>=p[1].offsetTop && p[0].offsetTop<=p[1].offsetTop+p[1].offsetHeight && p[0].offsetLeft+p[0].offsetWidth>=p[1].offsetLeft && p[0].offsetLeft<=p[1].offsetLeft+p[1].offsetWidth){
				console.log("你撞我了!再撞一个试试!")
			};
	}
	document.onmouseup=function(){
		document.onmousemove=null;
	}
}	
}
hit(p[0]);
hit(p[1]);
</script>
Copy after login

This article explains how to determine collision through JS. For more related content, please pay attention to the php Chinese website.

Related recommendations:

Introducing some js implementation solutions for classic algorithms

javascript Set as homepage and add to favorites JS code

Understanding of inheritance in JS



The above is the detailed content of Implement the method of determining collision through JS!. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template