Moving right immediately pushes div far off screen region - javascript

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",""));

Related

Need to find where 2 objects are located in Javascript

I'm trying to get 2 objects locations, so I can make the AI I coded to not walk through walls. My problem is that it's ignoring any extra if statements when I add them to the script.
function findEntities() { //Function for finding the players position and setting the playerLeft and playerTop variables
playerLeft = parseInt(player.style.left);
playerTop = parseInt(player.style.top);
enemyLeft = parseInt(enemy.style.left);
enemyTop = parseInt(enemy.style.top);
WallLeft = parseInt(wall.style.left);
WallTop = parseInt(wall.style.top);
chooseMovement();
setTimeout(findEntities, 1000) //starting a loop.
}
findEntities();
function chooseMovement() { //Chooses the direction to move, moves on X-axis first, then Y-axis
if((playerLeft - 64) > enemyLeft) || ((WallLeft - 64) != enemyLeft) {
Right();
} else if((playerLeft + 64) < enemyLeft) {
Left();
} else if((playerTop + 64) < enemyTop) {
Up();
} else if((playerTop - 64) > enemyTop) {
Down();
} else {
damagePlayer();
}}
function Right() { //Moves the enemy right
enemy.style.left = parseInt(enemy.style.left) + 64;
enemyLeft += 64;
}
function Left() { //Moves the enemy left
enemy.style.left = parseInt(enemy.style.left) - 64;
enemyLeft -= 64;
}
function Up() { //Moves the enemy up
enemy.style.top = parseInt(enemy.style.top) - 64;
enemyTop -= 64;
}
function Down() { //Moves the enemy down
enemy.style.top = parseInt(enemy.style.top) + 64;
enemyTop += 64;
}
I'm honestly not sure what exactly is giving you issues, but one thought is to maybe define the "checks" as their own function, for example:
function chooseMovement() {
if(checkMoveRight()) {
Right();
} else if((playerLeft + 64) < enemyLeft) {
Left();
} else if((playerTop + 64) < enemyTop) {
Up();
} else if((playerTop - 64) > enemyTop) {
Down();
} else {
damagePlayer();
}
}
function checkMoveRight(){
if(playerLeft - 64 > enemyLeft){ return true }
if(WallLeft - 64 != enemyLeft){ return true }
return false
}
This introduces it's own set of problems when it comes to complexity and state and what not but extracting things out into their own definitions rather than trying to have everything exist in the primary/singular if/else call thread might be useful.

Checking if two points are touching in a hex grid

Some time ago I wrote this fun grid that is offset to look like a hexagonal grid. I added a feature to check if any two points are touching. I thought it was brilliant until I finally found a bug and am not sure how to correct it.
If you press (1,4) and (2,5) you will see that they are "touching" but they shouldn't be. What logic am I missing in the function isTouchingHex?
Found bugs so far..
(1,4) & (2,5)
(2,2) & (3,3)
(0,0) & (1,1)
CodePen
var $point1 = $('#point1');
var $point2 = $('#point2');
var $dx = $('#dx');
var $dy = $('#dy');
var $isTouching = $('#isTouching');
var $table = $('#hexTable');
var table = [];
var rows = 10;
var cols = 5;
var point1 = null;
var point2 = null;
var clickedCount = 0;
for (let y = 0; y < rows; y++) {
var $tr = $('<div class="hexagonRow"></div>')
var row = [];
for (let x = 0; x < cols; x++) {
var $col = $('<div class="hexagon"><div class="hexagonText">' + x + ',' + y + '</div></div>');
$col.click(function() {
if (clickPoint(x, y))
$(this).toggleClass('clicked');
});
$tr.append($col);
row.push(y);
}
$table.append($tr);
table.push(row);
}
function clickPoint(x, y) {
var clicked = true;
if (point1 && point1[0] === x && point1[1] === y) {
point1 = null;
clickedCount--;
} else if (point2 && point2[0] === x && point2[1] === y) {
point2 = null;
clickedCount--;
} else if (!point1 && clickedCount < 3) {
point1 = [x, y];
clickedCount++;
} else if (!point2 && clickedCount < 3) {
point2 = [x, y];
clickedCount++;
} else {
clicked = false;
}
updateDisplay();
return clicked;
}
function updateDisplay() {
if (point1)
$point1.html(point1[0] + ',' + point1[1])
else
$point1.html('');
if (point2)
$point2.html(point2[0] + ',' + point2[1])
else
$point2.html('');
if (point1 && point2) {
var touching = isTouchingHex(point1[0], point1[1], point2[0], point2[1]) ? 'true' : 'false';
$isTouching.html(touching)
} else {
$isTouching.html('');
}
}
function isTouchingHex(x1, y1, x2, y2) {
var deltaX = x1 - x2;
var deltaY = y1 - y2;
$dx.html(deltaX);
$dy.html(deltaY);
// check same x
if (deltaX === 0) {
switch (deltaY) {
// check bottom left
case -1:
// check bottom
case -2:
// check top right
case 1:
// check above
case 2:
return true;
break;
}
} else if (deltaX === 1) {
switch (deltaY) {
// check bottom left
case -1:
// check top left
case 1:
return true;
break;
}
}else if (deltaX === -1) {
switch (deltaY) {
// check bottom right
case -1:
return true;
break;
}
}
return false;
}

Link the movement of a div to the movement of another 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);
}

Random "spawn" of divs

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;
}
}

How can I change background-position with arrow-keys?

Hi just started trying to learn a little javascript, now for my first programm I wanted to write code that moves the "background-position" when pressing arrow-keys.
So I hope one of you guys can help me to fix my code.
My (not so fancy) Code:
var x = 0;
var y = 0;
function GetChar (event){
var keyCode = ('which' in event) ? event.which : event.keyCode;
posy(move(keyCode, x, y))
posx(move(keyCode, x, y))
}
function move (key, x, y){
if (key === 38){
return y ++;
} if else (key === 40){
return y --;
} if else (key === 39){
return x ++;
} if else (key === 37){
return x --;
} else{
}
}
function posy(movy) {
return body.style.background-position-y + movy * 100;
}
function posx(movx) {
return body.style.background-position-x + movx * 100;
}
I ended up solving it with jQuery:
$(document).ready(function(){
var posx = 0;
var posy = 0;
$(document).keydown(function(e){
if(e.keyCode==40){
posy--;
console.log('down');
}else if(e.keyCode==38){
posy++;
console.log('up');
}else if(e.keyCode==39){
posx--;
console.log('right');
}else if(e.keyCode==37){
posx++;
console.log('left');
}else{
};
console.log(posy);
console.log(posx);
$('body').css('background-position-y', ''+posy*100+'px');
$('body').css('background-position-x', ''+posx*100+'px');
});
});

Categories