javascript - 当正方形到达 Canvas 底部时会卡住

标签 javascript html canvas game-physics

我正在尝试制作一个简单的基于 JavaScript 的游戏,用户将在 Canvas 周围移动方 block 并躲避朝它靠近的元素/方 block (但这只是一个计划,目前我还远远没有达到这一点) .

我遇到的问题是,每当我使 Canvas 宽度值大于高度时,它都会使正方形在到达页面底部后卡住。我的代码中可能有一个错误/错误,但我似乎没有发现任何东西。

代码可以找到here或如下:

    // This code was created in CodePen.io, so some parts of it might not make any sense,
    // nor are they gonna be useful outside the CodePen platform. Those parts are however only commented.

    var canvas = document.getElementById('canvas');
    var ctx = canvas.getContext('2d');
    // character data
    var charPositionX = canvas.width / 2;
    // Just for the snippet height
    var charPositionY = 0;
    //var deltaCharPositionX = 10;
    //var deltaCharPositionY = 10;

    //Removed the init() function, since the elements are loaded.

    // start creating elements, first the game environment.
    function draw() {
      clear();
      createRectangleToCoverCanvas();
      createChar(charPositionX, charPositionY, 10);
    }

    function clear() {
      ctx.clearRect(0, 0, canvas.width, canvas.height);
    }

    function createRectangleToCoverCanvas() {
      ctx.fillStyle = '#ddd';
      ctx.strokeStyle = '#ddd';
      ctx.beginPath();
      ctx.rect(0, 0, canvas.width, canvas.height);
      ctx.fill();
      ctx.stroke();
    }
    // now the character
    function createChar(x, y, radius) {
      ctx.fillStyle = 'white';
      ctx.strokeStyle = 'white';
      ctx.beginPath();
      ctx.rect(x, y, 32, 32);
      ctx.fill();
      ctx.stroke();
    }

    var raf, 
      direction = {
      x: 0,
      y: 0
    };
	
    // set the speed variable for the character
    var speed = 5;
    function triggerMoveChar(event) {
      switch (event.keyCode) {
        // left
        case 37:
          // update the direction object
          direction.x = -speed;
          // avoid the scrolling
          event.preventDefault();
          break;

        // up
        case 38:
          direction.y = -speed;
          event.preventDefault();
          break;

        // right
        case 39:
          direction.x = speed;
          event.preventDefault();
          break;
        
        //down
        case 40:
          direction.y = speed;
          event.preventDefault();
          break;
      }
      // if the animation haven't been initiated yet, and the direction is not 0, then do it now
      if (!raf && (direction.x || direction.y)) moveChar();
    }

    function releaseMoveChar(event) {
      switch (event.keyCode) {
        // left
        case 37:
          //reset this direction
          direction.x = 0;
          break;
        
        // up
        case 38:
          direction.y = 0;
          break;
        
        // right
        case 39:
          direction.x = 0;
          break;
        
        //down
        case 40:
          direction.y = 0;
          break;
      }
      if (!direction.x && !direction.y) {
        // if none of the directions is set, stop the animation
        cancelAnimationFrame(raf);
        raf = undefined;
      }
    }

    function moveChar() {
      // declare the animation function
      var move = function() {
        // update the positions without going out of the screen
        if(direction.x){
    	    if(
	    	  (charPositionX > 0 && charPositionX < canvas.width-32) ||
			    (charPositionX <= 0 && direction.x > 0) ||
			    (charPositionX >= canvas.width-32 && direction.x < 0))
				  charPositionX += direction.x;
		    }
      if(direction.y){
    	  if((charPositionY > 0 && charPositionY < canvas.height-32) ||
			    (charPositionY <= 0 && direction.y > 0) ||
			    (charPositionY >= canvas.width-32 && direction.y < 0))
				  charPositionY += direction.y;
		    }

        // finally draw ou character
        draw();
        // update the raf id
        raf = requestAnimationFrame(move);
      };
    // let's go !
    raf = requestAnimationFrame(move);
    }


    draw();

    window.addEventListener('keydown', triggerMoveChar, true);
    window.addEventListener('keyup', releaseMoveChar, true);
    canvas {
      margin: auto;
      position: absolute;
      left: 0;
      top: 0;
      right: 0;
      bottom: 0;
      border: 3px solid red;
    }

    body {
      background: #222;
    }

    .container {
      color: #999;
      margin: 0;
      padding: 10px 0px 20px;
      font-family: "Orbitron", "Helvetica", sans-serif;
      text-align: center;
      font-size: 11px;
      line-height: 16px;
    }

    .container h1 {
      margin: 10px 0;
      color: red;
      font-size: 32px;
      min-height: 430px;
    }

    .container h2 {
      margin: 10px 0;
      color: #ccc;
      font-size: 24px;
      min-height: 10px;
    }

    .container h3 {
      margin: 10px 0;
      color: #999;
      font-size: 18px;
    }
    <div class="container">
        <canvas id="canvas" width="640" height="416"></canvas>
        <h1>Project : Simple Game [v0.1alpha]</h1>
        <h2>CONTROLS: </h2>
        <h3>Arrow Keys </h3>
    </div>	

我将不胜感激任何帮助。

最佳答案

此行有一个拼写错误

if(direction.y){
          if((charPositionY > 0 && charPositionY < canvas.height-32) ||
                (charPositionY <= 0 && direction.y > 0) ||
                (charPositionY >= canvas.width-32 && direction.y < 0)) // here
                  charPositionY += direction.y;
            }

应该是height不是width .

(charPositionY >= canvas.height-32 && direction.y < 0))

关于javascript - 当正方形到达 Canvas 底部时会卡住,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55005687/

相关文章:

javascript - 在 ajax 进行时取消绑定(bind)事件处理程序

javascript - AngularJS:在使用 ng-src 指令时使用 $http 拦截器和 OAuth token

javascript - 有没有办法找到并删除所有 html 页面共有的未使用的 CSS 和 Javascript?

jquery - 在 JQuery 中的数组中搜索数组

html - 如何将 figcaption 从图中垂直放置?

javascript - Fabric js 如何设置百分比对象的位置

javascript - 重新渲染一个子组件(React with Hooks)

javascript - 检测何时支持带有 SVG 路径字符串的 Path2D

javascript - requestAnimationFrame 似乎很慢,cancelAnimationFrame 不起作用

javascript - 使用带有 Unicode 符号的 string.replace() Javascript 时出现问题