Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.7k views
in Technique[技术] by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...