Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Language: Web
Expertise: Advanced
Jan 20, 1999



Building the Right Environment to Support AI, Machine Learning and Deep Learning

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.
Steve Renaker
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date