JavaScript "if"조건이 작동하지 않음

FlipFloop

현재 HTML / SCSS 및 jQuery / JavaScript로 게임을 만들고 있습니다.

divjQuery로 키보드 화살표를 누를 때 움직이는 문자 가 있습니다. 이것은 if플레이어가 이동할 수있는 위치를 정의 하는 문과 함께 작동 하므로 더 큰 div.

나는 순수한 자바 스크립트 버전의 게임을 만들고 싶었고 플레이어는 if경계를 벗어나지 않도록 명령문을 넣는 경우를 제외하고는 모든 것을 움직일 수 있습니다 .

CodePen입니다

다음은 jQuery를 사용한 내 게임입니다.

var jQueryVersion = function() {
  var game_anim = function() {

    var level = [
      [0, 1, "l", 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, "l", "l", 1],
      [0, 0, 0, 0, 2, 2, 2, 2, 2, 2],
      [0, 0, 0, 0, 0, 3, 3, 0, 3],
    ];

    var $player = $("#player");
    var $game = $("#game");

    for (var i = 0; i < level.length; i++) {
      for (var j = 0; j < level[i].length; j++) {

        var n = level[i][j];

        if (n === 1) {
          $("<div>", {
            "class": "block stone ypos-0 xpos-" + [j]
          }).appendTo("#game");

        }

        if (n === 2) {
          $("<div>", {
            "class": "block stone ypos-1 xpos-" + [j]
          }).appendTo("#game");
        }
        if (n === 3) {
          $("<div>", {
            "class": "block stone ypos-2 xpos-" + [j]
          }).appendTo("#game");

        }

        if (n === 4) {
          $("<div>", {
            "class": "block stone ypos-3 xpos-" + [j]
          }).appendTo("#game");
        }

        if (n === "l") {
          $("<div>", {
            "class": "block lava ypos-" + [i] + " xpos-" + [j]
          }).appendTo("#game");
        }

      }
    }

    $(document).keydown(function(event) { // keycodes: left = 37, right = 39
      if (event.which == 39 || event.which == 68) { // right arrow or D
        if ($player.position().left < $game.width() - $player.width()) {
          $player.css("left", "+=10");
        }
      }
      if (event.which == 37 || event.which == 81 || event.which == 65) { // left arrow or Q on AZERTY or A on QWERTY
        if ($player.position().left > 0) {
          $player.css("left", "-=10");
        }
      }

      if (event.which == 38) {
        if ($player.position().top > 0) {
          $player.css("top", "-=10");
        }
      }
      if (event.which == 40) {
        if ($player.position().top < 500 - $player.height()) {
          $player.css("top", "+=10");
        }
      }

    });


  }

  $(document).ready(function() {

    game_anim();

  });
}
jQueryVersion();
#game {
  position: absolute;
  left: calc((100% - 800px)/2);
  height: 500px;
  width: 800px;
  border: 2px solid black;
}
.block {
  height: 50px;
  width: 50px;
  position: absolute;
}
.stone {
  background-color: black;
}
.lava {
  background-color: red;
}
#player {
  height: 50px;
  width: 50px;
  background-color: #3747C0;
  bottom: 0;
  position: absolute;
}
#player .eyes {
  border-radius: 50%;
  background-color: white;
  position: absolute;
  height: 10px;
  width: 10px;
}
#player .eye_R {
  left: 7px;
  top: 10px;
}
#player .eye_L {
  left: 32px;
  top: 10px;
}
#player .mouth {
  height: 8.5px;
  width: 32px;
  background-color: white;
  border-radius: 5px;
  left: calc((50px - 32px)/2);
  bottom: 10px;
  position: absolute;
}
.ypos-0 {
  bottom: 0px;
  position: absolute;
}
.ypos-1 {
  bottom: 50px;
  position: absolute;
}
.ypos-2 {
  bottom: 100px;
  position: absolute;
}
.ypos-3 {
  bottom: 150px;
  position: absolute;
}
.ypos-4 {
  bottom: 200px;
  position: absolute;
}
.ypos-5 {
  bottom: 250px;
  position: absolute;
}
.ypos-6 {
  bottom: 300px;
  position: absolute;
}
.ypos-7 {
  bottom: 350px;
  position: absolute;
}
.ypos-8 {
  bottom: 400px;
  position: absolute;
}
.xpos-0 {
  left: 0px;
  /*position: absolute;*/
}
.xpos-1 {
  left: 50px;
  /*position: absolute;*/
}
.xpos-2 {
  left: 100px;
  /*position: absolute;*/
}
.xpos-3 {
  left: 150px;
  /*position: absolute;*/
}
.xpos-4 {
  left: 200px;
  /*position: absolute;*/
}
.xpos-5 {
  left: 250px;
  /*position: absolute;*/
}
.xpos-6 {
  left: 300px;
  /*position: absolute;*/
}
.xpos-7 {
  left: 350px;
  /*position: absolute;*/
}
.xpos-8 {
  left: 400px;
  /*position: absolute;*/
}
.xpos-9 {
  left: 450px;
  /*position: absolute;*/
}
.xpos-10 {
  left: 500px;
  /*position: absolute;*/
}
.xpos-11 {
  left: 550px;
  /*position: absolute;*/
}
.xpos-12 {
  left: 600px;
  /*position: absolute;*/
}
.xpos-13 {
  left: 650px;
  /*position: absolute;*/
}
.xpos-14 {
  left: 700px;
  /*position: absolute;*/
}
.xpos-15 {
  left: 750px;
  /*position: absolute;*/
}
.xpos-16 {
  left: 800px;
  /*position: absolute;*/
}
.xpos-17 {
  left: 850px;
  /*position: absolute;*/
}
.xpos-18 {
  left: 900px;
  /*position: absolute;*/
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="game">
  <div id="player">
    <div class="eyes eye_R"></div>
    <div class="eyes eye_L"></div>
    <div class="mouth"></div>
  </div>
</div>



보시다시피, 캐릭터 / 플레이어는 상자에서 벗어나지 않고도 이동할 수 있습니다.

내 순수한 JavaScript가 작동하지 않는 이유는 무엇입니까?

다음은 JavaScript를 사용한 동일한 프로젝트입니다.

var javascriptVersion = function() {

	var game_anim = function() {

		var level = [
			[0, 1, "l", 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, "l", "l", 1],
			[0, 0, 0, 0, 2, 2, 2, 2, 2, 2],
			[0, 0, 0, 0, 0, 3, 3, 0, 3],
		];

		var player = document.getElementById('player');
		var game = document.getElementById("game");

		var left = 0;
		var top = 0;

		for (var i = 0; i < level.length; i++) {
			for (var j = 0; j < level[i].length; j++) {

				var n = level[i][j];

				if (n === 1) {

					var blocks = document.createElement("div");
					blocks.classList.add("block", "stone", "ypos-0", "xpos-" + j);
					game.appendChild(blocks);

				}

				if (n === 2) {
					var blocks = document.createElement("div");
					blocks.classList.add("block", "stone", "ypos-1", "xpos-" + j);
					game.appendChild(blocks);
				}
				if (n === 3) {
					var blocks = document.createElement("div");
					blocks.classList.add("block", "stone", "ypos-2", "xpos-" + j);
					game.appendChild(blocks);
				}

				if (n === 4) {
					var blocks = document.createElement("div");
					blocks.classList.add("block", "stone", "ypos-3", "xpos-" + j);
					game.appendChild(blocks);
				}

				if (n === "l") {
					var blocks = document.createElement("div");
					blocks.classList.add("block", "lava", "ypos-0", "xpos-" + j);
					game.appendChild(blocks);
				}

			}
		}

		document.addEventListener('keydown', function(event) { // keycodes: left = 37, right = 39
			if (event.keyCode == 39 || event.keyCode == 68) { // right arrow or D
				if (player.style.left < game.style.width - player.style.width) {
					left += 10;
					player.style.left = (parseInt(left) + left) + "px";
				}
			}
			if (event.keyCode == 37 || event.keyCode == 81 || event.keyCode == 65) { // left arrow or Q on AZERTY or A on QWERTY
				if (player.style.left > 0) {
					left -= 10;
					player.style.left = (parseInt(left) + left) + "px";
				}
			}

			if (event.keyCode == 38) {
				if (player.style.top > 0) {
					top -= 10;
					player.style.left = (parseInt(top) + top) + "px";
				}
			}
			if (event.keyCode == 40) {
				if (player.style.top < (500 - player.style.height)) {
					top += 10;
					player.style.left = (parseInt(top) + top) + "px";
				}
			}

		});

	}
	game_anim();
}

javascriptVersion();
#game {
  position: absolute;
  left: calc((100% - 800px)/2);
  height: 500px;
  width: 800px;
  border: 2px solid black;
}

.block {
  height: 50px;
  width: 50px;
  position: absolute;
}

.stone {
  background-color: black;
}

.lava {
  background-color: red;
}

#player {
  height: 50px;
  width: 50px;
  background-color: #3747C0;
  bottom: 0;
  position: absolute;
}
#player .eyes {
  border-radius: 50%;
  background-color: white;
  position: absolute;
  height: 10px;
  width: 10px;
}
#player .eye_R {
  left: 7px;
  top: 10px;
}
#player .eye_L {
  left: 32px;
  top: 10px;
}
#player .mouth {
  height: 8.5px;
  width: 32px;
  background-color: white;
  border-radius: 5px;
  left: calc((50px - 32px)/2);
  bottom: 10px;
  position: absolute;
}

.ypos-0 {
  bottom: 0px;
  position: absolute;
}

.ypos-1 {
  bottom: 50px;
  position: absolute;
}

.ypos-2 {
  bottom: 100px;
  position: absolute;
}

.ypos-3 {
  bottom: 150px;
  position: absolute;
}

.ypos-4 {
  bottom: 200px;
  position: absolute;
}

.ypos-5 {
  bottom: 250px;
  position: absolute;
}

.ypos-6 {
  bottom: 300px;
  position: absolute;
}

.ypos-7 {
  bottom: 350px;
  position: absolute;
}

.ypos-8 {
  bottom: 400px;
  position: absolute;
}

.xpos-0 {
  left: 0px;
  /*position: absolute;*/
}

.xpos-1 {
  left: 50px;
  /*position: absolute;*/
}

.xpos-2 {
  left: 100px;
  /*position: absolute;*/
}

.xpos-3 {
  left: 150px;
  /*position: absolute;*/
}

.xpos-4 {
  left: 200px;
  /*position: absolute;*/
}

.xpos-5 {
  left: 250px;
  /*position: absolute;*/
}

.xpos-6 {
  left: 300px;
  /*position: absolute;*/
}

.xpos-7 {
  left: 350px;
  /*position: absolute;*/
}

.xpos-8 {
  left: 400px;
  /*position: absolute;*/
}

.xpos-9 {
  left: 450px;
  /*position: absolute;*/
}

.xpos-10 {
  left: 500px;
  /*position: absolute;*/
}

.xpos-11 {
  left: 550px;
  /*position: absolute;*/
}

.xpos-12 {
  left: 600px;
  /*position: absolute;*/
}

.xpos-13 {
  left: 650px;
  /*position: absolute;*/
}

.xpos-14 {
  left: 700px;
  /*position: absolute;*/
}

.xpos-15 {
  left: 750px;
  /*position: absolute;*/
}

.xpos-16 {
  left: 800px;
  /*position: absolute;*/
}

.xpos-17 {
  left: 850px;
  /*position: absolute;*/
}

.xpos-18 {
  left: 900px;
  /*position: absolute;*/
}
<div id = "game">
	<div id = "player">
		<div class = "eyes eye_R"></div>
		<div class = "eyes eye_L"></div>
		<div class = "mouth"></div>
	</div>
</div>

도와 주셔서 감사합니다!

rckrd

Danny Drinkwater 의 답변이 지적했듯이 player.style.left$player.position().left. 자바 스크립트에 해당하는 것은 element.offsetLeft. jquery에서와 동일한 값을 얻지 못하는 몇 군데 더 있습니다.

다음은 vanilla js에 구현 된 keydown 핸들러의 예입니다 .

document.addEventListener('keydown', function(event) {
  event.preventDefault();
  if (event.keyCode == 39 || event.keyCode == 68) { // right arrow or D
    if (player.offsetLeft < game.getBoundingClientRect().width - player.getBoundingClientRect().width) {
      left = player.offsetLeft + 10;
      player.style.left = left.toString() + "px";
    }
  }
  if (event.keyCode == 37 || event.keyCode == 81 || event.keyCode == 65) { // left arrow or Q on AZERTY or A on QWERTY
    if (player.offsetLeft > 0) {
      left = player.offsetLeft - 10;
      player.style.left = left.toString() + "px";
    }
  }
  if (event.keyCode == 38) {
    if (player.offsetTop > 0) {
      top = player.offsetTop - 10;
      player.style.top = top.toString() + "px";
    }
  }
  if (event.keyCode == 40) {
    if (player.offsetTop < (500 - player.getBoundingClientRect().height)) {
      top = player.offsetTop + 10;
      player.style.top = top.toString() + "px";
    }
  }
});

이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.

침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제

에서 수정
0

몇 마디 만하겠습니다

0리뷰
로그인참여 후 검토

관련 기사

분류에서Dev

Javascript 조건문이 올바르게 작동하지 않음

분류에서Dev

JavaScript 버블 정렬 수정 ( "for"루프 조건이 작동하지 않음)

분류에서Dev

조건문이 작동하지 않음

분류에서Dev

JavaScript onsubmit preventDefault가 조건부로 작동하지 않음

분류에서Dev

조건이 작동하지 않는 경우 Javascript longhand

분류에서Dev

조건이 예상대로 작동하지 않는 경우 Javascript

분류에서Dev

Onclick이 작동하지 않음-Javascript

분류에서Dev

JavaScript "if"문이 작동하지 않음

분류에서Dev

JavaScript : setTimeout (setInterval)이 작동하지 않음

분류에서Dev

JavaScript : setTimeout (setInterval)이 작동하지 않음

분류에서Dev

JavaScript 구문이 작동하지 않음

분류에서Dev

NodeJS / JavaScript if 문이 작동하지 않음

분류에서Dev

같지 않은 조건이 작동하지 않음 Symfony2

분류에서Dev

Javascript, 조건이 && 논리 연산자없이 작동하면 &&가있을 때 작동하지 않습니다.

분류에서Dev

여러 조건이있는 if 문이 작동하지 않음

분류에서Dev

JavaScript 재귀 노드 동등 기능이 작동하지 않음

분류에서Dev

ngIf 다중 || (OR) 조건이 작동하지 않음

분류에서Dev

$ 또는 $ 내부 및 $ 필터 조건이 작동하지 않음

분류에서Dev

bash의 다중 if 조건이 작동하지 않음

분류에서Dev

두 번째 IF 조건이 제대로 작동하지 않음

분류에서Dev

SQL 쿼리 조건이 작동하지 않음

분류에서Dev

조건부 주석이 작동하지 않음

분류에서Dev

LINQ 조건부 Where 절이 작동하지 않음

분류에서Dev

MYSQL 및 조건이 작동하지 않음

분류에서Dev

제약 조건이 제대로 작동하지 않음

분류에서Dev

조건부 중단 점이 작동하지 않음

분류에서Dev

Netsuite 검색 필터 조건이 작동하지 않음

분류에서Dev

PostgreSQL LEFT OUTER JOIN 조건이 작동하지 않음

분류에서Dev

XSLT의 다중 조건이 작동하지 않음

Related 관련 기사

  1. 1

    Javascript 조건문이 올바르게 작동하지 않음

  2. 2

    JavaScript 버블 정렬 수정 ( "for"루프 조건이 작동하지 않음)

  3. 3

    조건문이 작동하지 않음

  4. 4

    JavaScript onsubmit preventDefault가 조건부로 작동하지 않음

  5. 5

    조건이 작동하지 않는 경우 Javascript longhand

  6. 6

    조건이 예상대로 작동하지 않는 경우 Javascript

  7. 7

    Onclick이 작동하지 않음-Javascript

  8. 8

    JavaScript "if"문이 작동하지 않음

  9. 9

    JavaScript : setTimeout (setInterval)이 작동하지 않음

  10. 10

    JavaScript : setTimeout (setInterval)이 작동하지 않음

  11. 11

    JavaScript 구문이 작동하지 않음

  12. 12

    NodeJS / JavaScript if 문이 작동하지 않음

  13. 13

    같지 않은 조건이 작동하지 않음 Symfony2

  14. 14

    Javascript, 조건이 && 논리 연산자없이 작동하면 &&가있을 때 작동하지 않습니다.

  15. 15

    여러 조건이있는 if 문이 작동하지 않음

  16. 16

    JavaScript 재귀 노드 동등 기능이 작동하지 않음

  17. 17

    ngIf 다중 || (OR) 조건이 작동하지 않음

  18. 18

    $ 또는 $ 내부 및 $ 필터 조건이 작동하지 않음

  19. 19

    bash의 다중 if 조건이 작동하지 않음

  20. 20

    두 번째 IF 조건이 제대로 작동하지 않음

  21. 21

    SQL 쿼리 조건이 작동하지 않음

  22. 22

    조건부 주석이 작동하지 않음

  23. 23

    LINQ 조건부 Where 절이 작동하지 않음

  24. 24

    MYSQL 및 조건이 작동하지 않음

  25. 25

    제약 조건이 제대로 작동하지 않음

  26. 26

    조건부 중단 점이 작동하지 않음

  27. 27

    Netsuite 검색 필터 조건이 작동하지 않음

  28. 28

    PostgreSQL LEFT OUTER JOIN 조건이 작동하지 않음

  29. 29

    XSLT의 다중 조건이 작동하지 않음

뜨겁다태그

보관