devxlogo

Collision Detection in DHTML

Collision Detection in DHTML

Collision detection is a fundamental part of game programming. It is also useful for many other aspects of user interface design. Being able to tell if one screen object has collided with another can help you solve any number of programming problems. Dynamic HTML allows developers to create client-side applications of a type that was once possible only with server-side programming. By combining JavaScript with Cascading Style Sheets, it’s possible to perform effective collision detection.

The following JavaScript example uses two screen elements (which could be images, layers, divs, or anything else in the document object hierarchy) called myObject1 and myObject2. The variables x and y hold either a true or a false value, depending on whether the two objects overlap on either the horizontal plane or the vertical plane. If both x and y evaluate to true, then the two objects have collided.

This example requires a version 4.0 or higher browser.

 x = ((myObject1.style.posLeft >= myObject2.style.posLeft) && (myObject.style.posLeft <= myObject2.style.posLeft));y = ((myObject.style.posTop  >= myObject2.style.posTop) &&   (myObject1.style.posTop <= myObject2.style.posTop));         if (x && y)    {	// Collision has occurred.    }
See also  Comparing different methods of testing your Infrastructure-as-Code
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist