Comparing Element ID's

I have used some code I found to try and detect shape collisions. When the ball hits the finish, it should move onto the next scene. I want to to compare the element ID to the correct one in order to move on.

  // Fetch physics engine for our hypeDocument
    	var hypeDocElm = document.getElementById(hypeDocument.documentId());
    	var engine = hypeDocument.getElementProperty(hypeDocElm, 'physics-engine')
    	
    	// Event listener
    	Matter.Events.on(engine, 'collisionStart', function(event) {
    	
    		// We know there was a collision so fetch involved elements ...
    		var aElm = document.getElementById(event.pairs[0].bodyA.elementId);
    		var bElm = document.getElementById(event.pairs[0].bodyB.elementId);
    		
    		// Now do something with the event and elements
    		
    		if (aElm.elementId() == "Ball" and bElm.elementId() == "Finish"){
    			hypeDocument.showNextScene();
    		}
    		else if (bElm.elementId() == "Ball" and aElm.elementId() == "Finish"){
    			hypeDocument.showNextScene();

    		}
    	});

Ball Bounce.hype.zip (47.7 KB)

I doesn't seem to work. If anyone could help me that would be great!

Hi,

Loads of syntax errors there.

The .elementId

This is not a call to get an id.
.elementId is a key name in the events object.
when you do something like

event.pairs[0].bodyA.elementId

You are traversing an object tree to get a value for the key.


To get the ids of hype elements you use .id

aElm.id


AND'ing in javascript uses two ampersands not the English word.

&&

bElm.id == "Ball" && aElm.id == "Finish"

The id you are comparing against are actually the display names in Hype not the ids?

In you project they are. "Level1Ball" & "Level1Finish"

	    if (aElm.id == "Level1Ball" &&  bElm.id == "Level1Finish"){
			hypeDocument.showNextScene();
			
		} 

Also not sure why your else if condition is needed ( and also is comparing the exact same condition )??


In your code you do not need to get the Hype element if all you are doing is comparing collision pair elementId.

You can simply just use the pair objects elementId

		// We know there was a collision so fetch involved elements ...
		var aElm = event.pairs[0].bodyA.elementId;
		var bElm = event.pairs[0].bodyB.elementId;
		
		// Now do something with the event and elements
		
		 
		if (aElm == "Level1Ball" &&  bElm == "Level1Finish"){
			hypeDocument.showNextScene();
			
		}
3 Likes