/    Sign up×
Community /Pin to ProfileBookmark

Help with JavaScript Code

I have successfully gotten two images to move I want to write generic code for the collision of any two pictures (opponents) for a game.

In this collision function I would like for two objects (their id’s) to be passed in . the function collects the boundaries, essentially and when there is a violation, there is an alert thrown.

/* css Define starting positions
#collision(obj1,obj2){{position:absolute; top:300px; left:900px }
#peter {position:absolute; top:50px; left:75px}
*
/

var topPeter = 25 // holds the value of the position *** same as CSS positions***
var leftPeter= 25
var stewietop = 300
var stewieleft = 900

function collision(obj1,obj2){
var o1t = obj1.top
var o1b = o1t + obj1.height
var o1l = obj1.left
var o1r = o1l + obj1.width
var o2t = obj2.top
var o2b = o2t + obj2.height
var o2l = obj2.left
var o2r = o2l + obj2.width

var test = false

/***** I have tested the following concept extensively and it works well. I am transferring it from a specific case involving the same two objects all the time to two random objects ********/

if( (((o1l >= o2l)&&(o1l <= o2r))||
((o2l >= o1l)&&(o2l <= o1r)))&&
(((o1t >= o2t)&&(o1t <= o2b))||
((o2t >= o1t)&&(o2t <= o1b)))
)
{test=true}
return test
}

// calling the function
if collision(peter,stewie) {alert(‘collision’)}

/* should throw an alert if the two touch each other.

to post a comment
JavaScript

0Be the first to comment 😎

×

Success!

Help @sirwebbie spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 6.1,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @meenaratha,
tipped: article
amount: 1000 SATS,

tipper: @meenaratha,
tipped: article
amount: 1000 SATS,

tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,
)...