Skip to content

Instantly share code, notes, and snippets.

@Bijesse
Created January 4, 2017 14:55
Show Gist options
  • Save Bijesse/aba7e686c0a2dd29ade370237117310e to your computer and use it in GitHub Desktop.
Save Bijesse/aba7e686c0a2dd29ade370237117310e to your computer and use it in GitHub Desktop.
Exported from Popcode. Click to import: https://popcode.org/?gist=aba7e686c0a2dd29ade370237117310e
<!DOCTYPE html>
<html>
<head>
<title>X movement Collision Left Only</title>
</head>
<body>
<!-- Put your page markup here -->
<div class="box" id="blue"></div>
<div class="box" id="red"></div>
</body>
</html>
{"enabledLibraries":["jquery"]}
function checkCollision() {
var blueLeft = $("#blue").offset().left;
var redLeft = $("#red").offset().left;
var blueRight = blueLeft + $("#blue").width();
var redRight = redLeft + $("#red").width();
if(blueRight > redLeft) {
alert("Touching");
}
}
$("body").keydown(function(event) {
//moves left
if (event.which === 37) {
$("#blue").css("left", $("#blue").offset().left - 40);
//moves right
} else if (event.which === 39) {
$("#blue").css("left", $("#blue").offset().left + 40);
} else {
return;
}
//Checks for position relative to each other
checkCollision();
});
.box {
height: 100px;
width: 100px;
position: absolute;
}
#blue {
background-color: rgba(0, 0, 255, 0.7);
z-index: 1;
}
#red {
background-color: red;
left: 50%;
margin-left: -50px;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment