Reputation: 646
I have a game, where you try to catch money. There is a canvas which has a ball on it. There is also money spawning as images, OUTSIDE of the canvas. I am trying to check the x and y coordinates of the ball and the x and y coordinates of an image to be the same. Below is a link to my code:
Here is what I think is important to this:
function checkif(){
for(var i = 0; i<document.getElementsByTagName('IMG').length; i++){
var x1 = document.getElementsByTagName('IMG')[i].style.left;
var x2 = x1.slice(0,x1.length-2)
var y2 = poss;
console.log(x2)
console.log(y2)
if(x2===x&&y2===y){
score = score+1;
document.getElementById('score').innerHTML = score;
}
}
}
If it doesnt help, the code is down below in the JsFiddle link: Thank you https://jsfiddle.net/1fdo9ctp/
Upvotes: 1
Views: 385
Reputation: 566
The problem is that you are trying to check if x and y positions are exactly the same which will almost never happen also it will not take the images binding box into account.
What you want to know is if the balls x intersects the money that it ball.x > money.x // you want the balls position to be higher then the money position && ball.x < money.x + money.width // you want the ball position to be lower then the money x + the moneys width, also the same for y position.
So in summary: The balls x,y should be inside the moneys box that is bigger then money.x and money.y and less then money.x+width and money.y+height
see this for examples https://developer.mozilla.org/en-US/docs/Games/Techniques/2D_collision_detection
Upvotes: 1