jQuery collision between two divs not working as expected - javascript

I am using the Jquery collision plugin from here and tried a fiddle here. I am trying to check the collision result when a user moves one object over the other. It is not working as expected and it throws an error stating collision is not defined.
Jquery Code
$(document).keydown(function(e) {
//Move arrow keys
if (e.keyCode === 37) {
$("#object1").animate({
left: "-=5"
}, 0);
}
if (e.keyCode === 38) {
$("#object1").animate({
top: "-=5"
}, 0);
}
if (e.keyCode === 39) {
$("#object1").animate({
left: "+=5"
}, 0);
}
if (e.keyCode === 40) {
$("#object1").animate({
top: "+=5"
}, 0);
}
var colliders_selector = "#object1";
var obstacles_selector = "#object2";
var hits = $(colliders_selector).collision(obstacles_selector);
alert(hits);
});
HTML code
<div id='object1'>
</div>
<div id='object2'>
</div>

Related

Using CSS transforms to translate/rotate sprite using arrow key inputs. Problem updating position

I am trying to control a Sprite using the arrow keys (UP/DOWN for Translation & LEFT/RIGHT for Rotation).
I need the sprite to translate in the direction it has been rotated in.
The issue is that when the sprite is rotated after the sprite has been translated, the position of the sprite resets to where it was originally. I have tried using one div for rotation and one div for translation to no success.
The problem I am facing is a little different to the usual "moving div around screen" issue because I need to move the div at angles and continue to move at that angle.
I feel I am overlooking a simple solution, I would really appreciate if someone could point me in the right direction! Is there an easier alternative to what I am attempting to do that someone could make me aware of?
I have created a JSFiddle to demonstrate what is going on:
CSS transform sprite fiddle
var r = document.getElementById("image2");
document.addEventListener("keyup", checkKeyUp);
document.addEventListener("keydown", checkKey);
var trany = 0;
var rotate = 0;
function checkKey(e) {
e = e || window.event;
if (e.keyCode == '38') {
// up arrow
trany = trany-1;
r.style.transform = 'rotate('+rotate+'deg)translateY('+trany+'vmin)';
}
else if (e.keyCode == '40') {
// down arrow
trany = trany+1;
r.style.transform = 'rotate('+rotate+'deg)translateY('+trany+'vmin)';
}
else if (e.keyCode == '37') {
// left arrow
rotate = rotate-.8;
r.style.transform = 'translateY('+trany+'vmin)rotate('+rotate+'deg)';
}
else if (e.keyCode == '39') {
// right arrow
rotate = rotate+.8;
r.style.transform = 'translateY('+trany+'vmin)rotate('+rotate+'deg)';
}
}
function checkKeyUp(e) {
e = e || window.event;
if (e.keyCode == '38') {
// up arrow
}
else if (e.keyCode == '40') {
// down arrow
}
else if (e.keyCode == '37') {
// left arrow
r.style.transform = 'translateY('+trany+'vmin)rotate('+rotate+'deg)';
}
else if (e.keyCode == '39') {
// right arrow
r.style.transform = 'translateY('+trany+'vmin)rotate('+rotate+'deg)';
}
}
#myAnimation {
top:250px;
left:250px;
position: absolute;
}
#image2 {
width:40%
}
img {
width: 30%;
}
<!DOCTYPE html>
<html>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<body>
<div id ="myContainer">
<div id="image1" style="height:300px;width:500px; background-
color:red;"></div>
</div>
<div id ="myAnimation">
<image id="image2" src="https://banner2.kisspng.com/20180415/pge/kisspng-arrow-desktop-wallpaper-symbol-clip-art-up-arrow-5ad37ddc82f384.4572004515238097565364.jpg" style="bottom:0px;width:10%"></image>
</div>
</body>
</html>
what you want to achieve is to move your element independently from its previous state and this cannot be achieved using only transform since transform always consider the initial state in order to move your element.
An idea is to consider using bottom/left to move the element and use only transform to rotate the element. The angle of rotation will define how you will adjust the bottom and left properties:
var r = document.getElementById("image2");
document.addEventListener("keydown", checkKey);
var rotate = 0;
var left=0;
var bottom= 0;
function checkKey(e) {
e = e || window.event;
if (e.keyCode == '38') {
// up arrow
r.style.left = left + Math.sin(rotate*Math.PI/180) + 'px';
r.style.bottom = bottom + Math.cos(rotate*Math.PI/180) + 'px';
} else if (e.keyCode == '40') {
// down arrow
r.style.left = left - Math.sin(rotate*Math.PI/180) + 'px';
r.style.bottom = bottom - Math.cos(rotate*Math.PI/180) + 'px';
} else if (e.keyCode == '37') {
// left arrow
rotate = rotate - .8;
r.style.transform = 'rotate(' + rotate + 'deg)';
} else if (e.keyCode == '39') {
// right arrow
rotate = rotate + .8;
r.style.transform = 'rotate(' + rotate + 'deg)';
}
left = parseFloat(r.style.left);
bottom = parseFloat(r.style.bottom);
}
#image2 {
width: 40px;
position: absolute;
}
<img id="image2" src="https://banner2.kisspng.com/20180415/pge/kisspng-arrow-desktop-wallpaper-symbol-clip-art-up-arrow-5ad37ddc82f384.4572004515238097565364.jpg" style="left:0;bottom:0;">
To fix this problem we need to understand how transform works. It does each step one by one. If we want, for example to move diagonally, first we need to rotate, then translate. If we want to make the next move, our previous steps need to be saved. If we don't remember them, the arrow will be animated from the beginning.
So, on each animation end (key up) we need to save all the previous steps.
The next step is all the previous steps + translate/rotate.
Here is your code that I think is working correctly:
var r = document.getElementById("image2");
document.addEventListener("keyup", checkKeyUp);
document.addEventListener("keydown", checkKey);
var saved_moves = '';
var trany = 0;
var rotate = 0;
function checkKey(e) {
e = e || window.event;
if (e.keyCode == '38') {
// up arrow
trany = trany-1;
r.style.transform = saved_moves + 'translateY('+trany+'vmin)';
}
else if (e.keyCode == '40') {
// down arrow
trany = trany+1;
r.style.transform = saved_moves + 'translateY('+trany+'vmin)';
}
else if (e.keyCode == '37') {
// left arrow
rotate = rotate-2;
r.style.transform = saved_moves + 'rotate('+rotate+'deg)';
}
else if (e.keyCode == '39') {
// right arrow
rotate = rotate+2;
r.style.transform = saved_moves + 'rotate('+rotate+'deg)';
}
}
function checkKeyUp(e) {
e = e || window.event;
if (e.keyCode == '37' || e.keyCode == '38' || e.keyCode == '39' || e.keyCode == '40') {
// every arrow
saved_moves = r.style.transform;
// reset trany and rotate values
trany = 0;
rotate = 0;
}
}
You can check this jsfiddle https://jsfiddle.net/cyv0j1du/49/
EDIT
Becouse the solution above would create a very long transform, I've came up with different solution. When you release the key, app is reading the matrix value, and then it changes the arrow top and left value. Now only rotate value is remembered.
// Based on the absolute position you've chosen
var left = 250;
var top = 250;
function checkKeyUp(e) {
e = e || window.event;
if (e.keyCode == '37' || e.keyCode == '38' || e.keyCode == '39' || e.keyCode == '40') {
var matrix = window.getComputedStyle(r).getPropertyValue('transform');
matrix = matrix.slice(0, -1);
var values = matrix.split(',');
var x = values[4];
var y = values[5];
top += parseInt(y);
left += parseInt(x);
r.style.top = top + 'px';
r.style.left = left + 'px';
r.style.transform = 'rotateZ('+rotate+'deg)';
trany = 0;
}
}
I've also deleted #myAnimation
#image2 {
width: 20%;
position: absolute;
top: 250px;
left: 250px;
}
so I've deleted the div
<image id="image2" src="https://banner2.kisspng.com/20180415/pge/kisspng-arrow-desktop-wallpaper-symbol-clip-art-up-arrow-5ad37ddc82f384.4572004515238097565364.jpg" style="bottom:0px;width:10%"></image>
You can check how it works here:
https://jsfiddle.net/w1ox240m/57/

left right down up keyboard to move an object using JS

I want to make an image moving on the screen up down right and left.
it only moves up and down
I can't fix my code
here is what I was working on so far
frame.on ("keydown", function(e) {
zog(e.keyCode); // e is an event object
if (e.keyCode == 38) {
dir = -1;
} else if(e.keyCode == 40){
dir = 1;
} else if (e.keyCode == 37){ //left
dir = 0;
} else if (e.keyCode == 39){ //right
dir = 0;
}
});
frame.on ("keyup", function() {
dir = 0;
});
The following will update the box position every time you press the arrow buttons on your keyboard. Keep in mind up/down will make the page scroll up/down. But that's a diff problem to solve ;)
(function($){$(function(){
var box = $('.box');
$('body').on('keyup', function(e){
if (e.keyCode == 38) {
box.css('top', box.offset().top - 1);
} else if(e.keyCode == 40){
box.css('top', box.offset().top + 1);
} else if (e.keyCode == 37){ //left
box.css('left', box.offset().left - 1);
} else if (e.keyCode == 39){ //right
box.css('left', box.offset().left + 1);
}
});
})})(jQuery);
.box {
width: 100px;
height: 100px;
border: 1px solid #000;
position: absolute;
top: 0px;
left: 0px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="box"></div>

div cannot animate bottom side and goes outside from window screen from every side

this is working fine with left,right and top animate div move from left side, right side and top side but it is not working with bottom side div can not move bottom. and also when i press key more than ten time or more quikly it goes outside from my window screen from every side and if i press key after one animation finish it can not goes out side.
my html code:
<body>
<div class="block"></div>
</body>
my css code:
div {
position: absolute;
background-color: #abc;
left: 50px;
top:50px;
width: 100px;
height: 100px;
}
my jquery code:
$(window).load(function(e) {
$("body").keydown(function(e) {
var width1 = $(window).width();
var heigth1 = $(window).height();
if(e.keyCode == 37) { // left
if (parseInt($('.block').css('left')) >= 50) {
$('.block').animate({left: '-=50'},"slow");
}
}
else if(e.keyCode == 39) { // right
if (parseInt($('.block').css('left')) <= (width1 - 150)){
$(".block").animate({left: "+=50px"},'slow');
}
}
else if(e.keyCode == 40){ // bottom
if (parseInt($('.block').css('top')) <= (height1 - 150)) {
$(".block").animate({'top':'+=50px'},'slow');
}
}
else if(e.keyCode == 38){ // top
if (parseInt($('.block').css('top')) >= 50) {
$(".block").animate({'top':'-=50px'},'slow');
}
}
});
});
there is my example, hope i help you :)
example
:)
Typo!
var heigth1 = $(window).height();
should be
var height1 = $(window).height();

stop animate outside of my window screen

this is working fine with left animate div cannot goes outside from left side but it is not working with right side div goes outside of window screen.
my html code:
<body>
<div class="block"></div>
</body>
my css code:
div {
position: absolute;
background-color: #abc;
left: 50px;
top:50px;
width: 90px;
height: 90px;
margin: 5px;
}
my jquery code
$("body").keydown(function(e) {
var width = $(window).width();
var heigth = $(window).height();
if(e.keyCode == 37) { // left
if (parseInt($('.block').css('left')) >= 50) {
$('.block').animate({left: '-=50'},"slow");
}
}
else if(e.keyCode == 39) { // right
if (parseInt($('.block').css('left')) <= width) {
$(".block").animate({left: "+=50px"},'slow');
}
}
});
thanks in advance.
When comparing the current left value to window width, you're not adding the 50px that will be added as the result of the function, thus you will go outside the width of the window.
You should also account for the width of the .block element itself
//...
else if(e.keyCode == 39) { // right
if ((parseInt($('.block').css('left')) + 50 + $('.block').width()) <= width) {
$(".block").animate({left: "+=50px"},'slow');
}
}
//...
Improve some code to #lukiffer's answer.
//...
else if(e.keyCode == 39) { // right
if (parseInt($('.block').css('left')) <= (width-150) ) {
$(".block").animate({left: "+=50px"},'slow');
}
}
//...

Change background-position on keypress

I am new to javascript games.
I have an idea of game, As an example if I am taking Solidsnake's character.
I want character view changes on pressing navigation keys.
If I press left key it should show left view, right key for right view and so on.
How do i get change in image on pressing keys , how can I do this in javascript?
Idea of game-
Code in brief-
var leftKey,upKey,rightKey,downKey;
var box = $("#plane"),
left = 37,
up = 38,
right = 39,
down = 40;
function key(e) {
console.log(e.keyCode);
var $key = e.keyCode;
$(document).keydown(function(e) {
if (e.keyCode == left)
leftKey = true;
if (e.keyCode == up)
upKey = true;
if (e.keyCode == right)
rightKey = true;
if (e.keyCode == down)
downKey = true;
}).keyup(function(e) {
if (e.keyCode == left)
leftKey = false;
if (e.keyCode == up)
upKey = false;
if (e.keyCode == right)
rightKey = false;
if (e.keyCode == down)
downKey = false;
});
}
$("body").keydown(function(){
key(event);
});
setInterval(function() {
if (upKey) {
box.css("top", "-=10");
}
if (rightKey) {
box.css("left", "+=10");
}
if (downKey) {
box.css("top", "+=10");
}
if (leftKey) {
box.css("left", "-=10");
}
},20);
Right now i have this code with simple navigation moves.
Js fiddle
You can do this with CSS to set it right and avoid multiple image requests. You need to have a sprite with all images of the character in a row and then mask with a div the area you need to show. Then with javascript you can change the position of the image either by using marginLeft or marginRight or left and right (you need to set position relative or absolute for left and right).
When you do e.keyCode == up and the like, you can change the image source then:
if (e.keyCode == up) {
upKey = true;
$("#plane").attr('src', 'up-img-src');
}
Either do this: http://jsfiddle.net/VMM5P/1/
Change the image src on keypress:
if (upKey) {
box.attr("src", "http://cdn3.iconfinder.com/data/icons/blackblue/128/iChat.png");
}
if (rightKey) {
box.attr("src", "http://cdn2.iconfinder.com/data/icons/blackblue/128/guitar.png");
}
if (downKey) {
box.attr("src", "http://cdn3.iconfinder.com/data/icons/blackblue/128/TextEdit.png");
}
if (leftKey) {
box.attr("src", "http://cdn2.iconfinder.com/data/icons/blackblue/128/preview.png");
}
or you can make a sprite and position them accordingly:
Suppose box is the div which has a background sprite image
if (upKey) {
box.css("background-position", "0px 0px"); // pos 1
}
if (rightKey) {
box.css("background-position", "120px 0px"); // pos 2
}
if (downKey) {
box.css("background-position", "240px 0px"); // pos 3
}
if (leftKey) {
box.css("background-position", "360px 0px"); // pos 4
}
You would want to change the attr source for the image.
if (leftKey) {
box.find('img').attr('src', 'ENTER NEW IMAGE URL HERE');
}

Categories