I'm trying to create a "spawn point" for a div. I have made it work and I have a working collision detector for it. There are two things I wanted to ask regarding my code.
How do I get my code to work with more than one player (window.i). - At the moment, after an hour of fiddling, I've only broken my code. This whole area screws up the collision detector, I have more than one player showing at times, but I'm unable to move.
How do I make it so that it detects the contact before it happens - I've tried working with the "tank's" margin and subtracting it's width, so that before it makes contact it calls an event, but it has been unsuccessful and completely stopped the collision function working.
I'm sorry that it's asking a lot, I really do understand that, but the issues come into eachother and rebound off so I thought it was best I put it all into one question rather than 2 separate ones an hour apart.
function animate() {
var tank = document.createElement("div");
tank.id= "tank";
tank.style.marginLeft="0px";
tank.style.marginTop="0px";
tank.style.height="10px";
tank.style.width="10px";
document.body.appendChild(tank);
x = parseInt(tank.style.marginLeft);
y = parseInt(tank.style.marginTop);
document.onkeydown = function () {
e = window.event;
if (e.keyCode == '37') {
if (x > 0) {
if (collisionDetector() == false) {
x = x - 10;
tank.style.marginLeft = x + "px";
} else {
alert();
}
}
} else if (e.keyCode == '39') {
if (x < 790) {
if (collisionDetector() == false) {
x = x + 10;
tank.style.marginLeft = x + "px";
} else {
alert();
}
}
} else if (e.keyCode == '38') {
if (y > 0) {
if (collisionDetector() == false) {
y = y - 10;
tank.style.marginTop = y + "px";
} else {
alert();
}
}
} else if (e.keyCode == '40') {
if (y < 490) {
if (collisionDetector() == false) {
y = y + 10;
tank.style.marginTop = y + "px";
} else {
alert();
}
}
}
}
}
window.lives = 3;
function playerSpawn() {
window.i = 1;
while (i > 0) {
var player = document.createElement("div");
randMarL = Math.ceil(Math.random()*80)*10;
randMarT = Math.ceil(Math.random()*50)*10;
player.id = "player";
player.style.marginLeft= randMarL + "px";
player.style.marginTop= randMarT + "px";
player.style.height="10px";
player.style.width="10px";
document.body.appendChild(player);
i--;
}
}
function collisionDetector() {
x1 = tank.style.marginLeft;
x2 = player.style.marginLeft;
y1 = tank.style.marginTop;
y2 = player.style.marginTop;
if ((x1 == x2 && y1 == y2)) {
return true;
} else {
return false;
}
}
Related
I was looking into one of the only few full page scroll codes which I have found so far, and wanted to somehow get the idea of what I should do by reversing the engineering but I'm noob and not good at understanding it pretty well, I don't understand it well and I get stock at every line, can you please explain to me what the guy has done? Whats the basics of what he is doing ..variables and functions and what they are in this case and why we need them? A summary on what is going on.
this is the link to the code
https://codepen.io/igstudio/pen/pbYOab
this is the JS code
(function() {
"use strict";
/*[pan and well CSS scrolls]*/
var pnls = document.querySelectorAll('.panel').length,
scdir, hold = false;
function _scrollY(obj) {
var slength, plength, pan, step = 100,
vh = window.innerHeight / 100,
vmin = Math.min(window.innerHeight, window.innerWidth) / 100;
if ((this !== undefined && this.id === 'well') || (obj !== undefined && obj.id === 'well')) {
pan = this || obj;
plength = parseInt(pan.offsetHeight / vh);
}
if (pan === undefined) {
return;
}
plength = plength || parseInt(pan.offsetHeight / vmin);
slength = parseInt(pan.style.transform.replace('translateY(', ''));
if (scdir === 'up' && Math.abs(slength) < (plength - plength / pnls)) {
slength = slength - step;
} else if (scdir === 'down' && slength < 0) {
slength = slength + step;
} else if (scdir === 'top') {
slength = 0;
}
if (hold === false) {
hold = true;
pan.style.transform = 'translateY(' + slength + 'vh)';
setTimeout(function() {
hold = false;
}, 1000);
}
console.log(scdir + ':' + slength + ':' + plength + ':' + (plength - plength / pnls));
}
/*[swipe detection on touchscreen devices]*/
function _swipe(obj) {
var swdir,
sX,
sY,
dX,
dY,
threshold = 100,
/*[min distance traveled to be considered swipe]*/
slack = 50,
/*[max distance allowed at the same time in perpendicular direction]*/
alT = 500,
/*[max time allowed to travel that distance]*/
elT, /*[elapsed time]*/
stT; /*[start time]*/
obj.addEventListener('touchstart', function(e) {
var tchs = e.changedTouches[0];
swdir = 'none';
sX = tchs.pageX;
sY = tchs.pageY;
stT = new Date().getTime();
//e.preventDefault();
}, false);
obj.addEventListener('touchmove', function(e) {
e.preventDefault(); /*[prevent scrolling when inside DIV]*/
}, false);
obj.addEventListener('touchend', function(e) {
var tchs = e.changedTouches[0];
dX = tchs.pageX - sX;
dY = tchs.pageY - sY;
elT = new Date().getTime() - stT;
if (elT <= alT) {
if (Math.abs(dX) >= threshold && Math.abs(dY) <= slack) {
swdir = (dX < 0) ? 'left' : 'right';
} else if (Math.abs(dY) >= threshold && Math.abs(dX) <= slack) {
swdir = (dY < 0) ? 'up' : 'down';
}
if (obj.id === 'well') {
if (swdir === 'up') {
scdir = swdir;
_scrollY(obj);
} else if (swdir === 'down' && obj.style.transform !== 'translateY(0)') {
scdir = swdir;
_scrollY(obj);
}
e.stopPropagation();
}
}
}, false);
}
/*[assignments]*/
var well = document.getElementById('well');
well.style.transform = 'translateY(0)';
well.addEventListener('wheel', function(e) {
if (e.deltaY < 0) {
scdir = 'down';
}
if (e.deltaY > 0) {
scdir = 'up';
}
e.stopPropagation();
});
well.addEventListener('wheel', _scrollY);
_swipe(well);
var tops = document.querySelectorAll('.top');
for (var i = 0; i < tops.length; i++) {
tops[i].addEventListener('click', function() {
scdir = 'top';
_scrollY(well);
});
}
})();
Thanks.
I have plugin jQuery-splitter that bind to document.documentElement:
$(document.documentElement).bind('mousedown.splitter touchstart.splitter', function(e) {
if (splitter_id !== null) {
current_splitter = splitters[splitter_id];
$('<div class="splitterMask"></div>').css('cursor', current_splitter.children().eq(1).css('cursor')).insertAfter(current_splitter);
current_splitter.settings.onDragStart(e);
}
}).bind('mouseup.splitter touchend.splitter touchleave.splitter touchcancel.splitter', function(e) {
if (current_splitter) {
$('.splitterMask').remove();
current_splitter.settings.onDragEnd(e);
current_splitter = null;
}
}).bind('mousemove.splitter touchmove.splitter', function(e) {
if (current_splitter !== null) {
var limit = current_splitter.limit;
var offset = current_splitter.offset();
if (current_splitter.orientation == 'vertical') {
var pageX = e.pageX;
if(e.originalEvent && e.originalEvent.changedTouches){
pageX = e.originalEvent.changedTouches[0].pageX;
}
var x = pageX - offset.left;
if (x <= current_splitter.limit) {
x = current_splitter.limit + 1;
} else if (x >= current_splitter.width() - limit) {
x = current_splitter.width() - limit - 1;
}
if (x > current_splitter.limit &&
x < current_splitter.width()-limit) {
current_splitter.position(x, true);
current_splitter.find('.splitter_panel').
trigger('splitter.resize');
//e.preventDefault();
}
} else if (current_splitter.orientation == 'horizontal') {
var pageY = e.pageY;
if(e.originalEvent && e.originalEvent.changedTouches){
pageY = e.originalEvent.changedTouches[0].pageY;
}
var y = pageY-offset.top;
if (y <= current_splitter.limit) {
y = current_splitter.limit + 1;
} else if (y >= current_splitter.height() - limit) {
y = current_splitter.height() - limit - 1;
}
if (y > current_splitter.limit &&
y < current_splitter.height()-limit) {
current_splitter.position(y, true);
current_splitter.find('.splitter_panel').
trigger('splitter.resize');
//e.preventDefault();
}
}
current_splitter.settings.onDrag(e);
}
});
And in user code when I use this code the click don't work when I click on splitter (div between panels) it work when I click on the panel.
var counter = 0;
$(document.documentElement).on('click', function(e) {
console.log('x');
var $target = $(e.target);
if ($target.is('.vsplitter, .hsplitter')) {
if (++counter == 2) {
console.log('double click');
$target.parents('.splitter_panel').eq(0).data('splitter').position(20);
counter = 0;
}
} else {
counter = 0;
}
});
When I comment out the $(document.documentElement).bind('mousedown.splitter touchstart.splitter' code I can double click on the splitter. Anybody have a clue why is this happening?
It was caused by .splitterMask div.
I'm making an alcohol simulator, so when I press a button, you see an alcohol bottle being drained, but at the same time I should see the stomach filling. I have a code already for 'drinking', but I want to fix that if the water of the bottle moves 2 steps, that the water of the stomach only moves one step. I'll put just the js here, if you want the html as well, let me know.
var top_max = 475,
top_min = 400,
left_max = 200;
function move_img(str) {
var step = 1; // change this to different step value
var el = document.getElementById('i1');
var el2 = document.getElementById('i2');
if (str == 'up' || str == 'down') {
var top = el.offsetTop;
var height = el.offsetHeight;
console.log(height);
if (str == 'up') {
top -= step;
height += step;
} else {
top += step;
height -=step;
}
if (top_max >= top && top >= 110) {
document.getElementById('i1').style.top = top + "px";
document.getElementById('i1').style.height = height;
} else {
clearInterval(myVar)
}
} else if (str == 'left' || str == 'right') {
var left = el.offsetLeft;
if (str == 'left') {
left += step;
} else {
left -= step;
}
if (top_left < left && left >= 0) {
document.getElementById('i1').style.left = top + "px";
} else {
clearInterval(myVar)
}
}
}
function auto(str) {
myVar = setInterval(function () {
move_img(str);
}, 90);
}
function nana() {}
var myVar;
function handler() {
clearInterval(myVar);
auto(this.id);
}
function auto(str) {
myVar = setInterval(function(){ move_img(str); }, 2) ;
}
function stop(){
setTimeout(function( ) { clearInterval( myVar ); }, 1);
}
This is a script that I'm using for a slider. In this slider I've 2 button left and right for visit the slides. I've used jQuery and a bit of Javascript for do this. I'm using a button for play/pause but after the 3rd time the slider crash and it goes really fast.
The button
<input type="button" class="pausa" value="PAUSE" />
The script
$(document).ready(function(){
var one = "label#arrow-";
var x = 2;
var y = 0;
var two = ".arrows";
function clickin() {
if(jQuery('.pausa').data('clicked')) {
jQuery('.pausa').click(function(){
$(this).data('clicked', false);
$(this).val('PAUSE');
return setTimeout(clickin, 4000);
});
}
else {
while ((x != 7) && (y == 0)) {
$(one + x + two).trigger('click');
x++;
if (x != 7)
return setTimeout(clickin, 4000);
}
if (x == 7) {
y = 1;
x = 5;
}
while ((x != 0) && (y == 1)) {
$(one + x + two).trigger('click');
x--;
if (x != 7)
return setTimeout(clickin, 4000);
}
if (x == 0) {
y = 0;
x = 2;
return setTimeout(clickin, 4000);;
}
}
}
setTimeout(clickin, 4000);
jQuery('.pausa').click(function(){
$(this).data('clicked', true);
$(this).val('PLAY');
return clickin();
});
});
I've fixed it:
You can check the complete code here
$(document).ready(function(){
var one = "label#arrow-";
var two = ".arrows";
var x = 2; //Value of the button
var point = 0; //Check if you are pressing for play or pause
function clickin() {
if(point % 2)
$('.pausa').val('PLAY'); //Rotation Pause
else
$('.pausa').val('PAUSA'); //Rotation Play
if(!(point % 2)) //If it's in Play (Pause for button)
{
$(one + x + two).trigger('click');
x++;
if(x == 7)
x = 1;
return setTimeout(clickin, 4000)
}
else return 1; //If it's in Pause (Play for button)
}
setTimeout(clickin, 4000);
jQuery('.pausa').click(function(){ //Waiting input click
point++;
return clickin()
});
});
When I attempt to move the div (tank) to the right ONLY in the first "movement command", and only in that direction, I come across in issue whereby my div shoots off a few thousand pixels to the right, way off of the screen region. Was hoping someone would assist me to see why this is.
function animate() {
var tank = document.getElementById("tank");
tank.style.marginLeft="360px";
tank.style.marginTop="440px";
window.xpos = tank.style.marginLeft;
window.ypos = tank.style.marginTop;
window.x = xpos.replace("px","");
window.y = ypos.replace("px","");
document.onkeydown = checkKey;
function checkKey(e) {
e = e || window.event;
if (e.keyCode == '37') {
if (x > 0) {
x = x - 20;
tank.style.marginLeft = x + "px";
}
} else if (e.keyCode == '39') {
if (x < 70) {
x = x + 20;
tank.style.marginLeft = x + "px";
}
} else if (e.keyCode == '38') {
if (y > 0) {
y = y - 20;
tank.style.marginTop = y + "px";
}
} else if (e.keyCode == '40') {
if (y < 440) {
y = y + 20;
tank.style.marginTop = y + "px";
}
}
}
checkKey(e);
}
window.lives = 3;
function destroy() {
if (lives != 0) {
alert("Life Lost!");
lives--;
window.collision == false;
animate();
} else {
alert("Try Again!");
}
}
window.collision = true;
function state() {
if (collision == false) {
window.state = 1;
} else if (collision == true) {
window.state = 0;
}
return state;
}
state();
if (state == 1) {
animate();
} else {
destroy();
}
You think you are doing a math operation but what you really are doing a string concatenation. In Javascript "360"-20 equals 340 because in this case the string is converted to a number and then an arithmetic subtraction is performed with both numeric values, however a different set of rules apply for the plus operator: in this case "360"+20 yields "36020" because the number is converted to a string and then both strings are concatenated.
Do this:
window.x = Number(xpos.replace("px",""));
window.y = Number(ypos.replace("px",""));