JavaScript画布来回移动矩形

时间:2018-11-10 00:57:48

标签: javascript canvas game-physics

我现在正在用JavaScript制作2D平台游戏,到目前为止,除了移动我的第一个平台外,一切都可以正常工作

<!DOCTYPE html>
<html>

<body>

  <style>
    canvas {
      background: #eee;
    }
  </style>

  <canvas id="ctx" tabindex=0 width=900 height=500 style="border:1px solid #000000;" onkeypress="movePlayer(event)" onkeyup="keyUp(event)"></canvas>

  <script>
    var canvas = document.getElementById("ctx");
    var ctx = canvas.getContext("2d");
    canvas.setAttribute('tabindex', 0);
    canvas.focus();
    canvas.addEventListener("keydown", movePlayer);

    //Maybe I can get a class working?

    class Platform {
      constructor(x, y, xS, yS, moveBool) {
        this.xPos = x;
        this.yPos = y;
        this.xSize = xS;
        this.ySize = yS;

        ctx.fillStyle = "red";
        ctx.fillRect(this.xPos, this.yPos, this.xSize, this.ySize);

        this.moveable = moveBool;
      }

      get getX() {
        return this.xPos;
      }
      get getY() {
        return this.yPos;
      }
      get getxSize() {
        return this.xSize;
      }
      get getySize() {
        return this.ySize;
      }
      get getMoveable() {
        return this.moveable;
      }

      set moveRight(speed) {
        this.xPos = speed;
      }
    }

    //Platform array:
    platformArray = [];

    //Vars:

    var x_new = 50;
    var y_new = 50;

    var isJumping = false;
    var isColliding = false;

    var speed = 10;

    //Moving platform vars:
    var plat1X = 100;

    var keys = {
      up: false,
      right: false,
      left: false
    };

    function movePlayer(event) {
      switch (event.keyCode) {
        //Right key down:
        case 39:
          keys["right"] = true;
          break;
          //Left key down:
        case 37:
          keys["left"] = true;
          break;
          //Up key down:
        case 38:
          keys["up"] = true;
          isJumping = true;
          break;
      }
    }

    function keyUp(event) {
      switch (event.keyCode) {
        //Up key up:
        case 38:
          isJumping = false;
          keys["up"] = false;
          break;
          //Right key up:
        case 39:
          keys["right"] = false;
          break;
          //Left key up:
        case 37:
          keys["left"] = false;
          break;
      }

    }

    function boundsIntersect(x1, y1, x2, y2) {
      if (x1 > x2 - 50 && x1 < x2 + 200 && y1 < y2 && y1 > y2 - 55) {
        return true;
      }
      return false;
    }

    function update() {
      window.requestAnimationFrame(update);
      ctx.clearRect(0, 0, 900, 500);
      ctx.fillStyle = "black";
      ctx.beginPath();
      ctx.fillRect(x_new, y_new, 50, 50);
      //Draw ground:
      ctx.beginPath();
      ctx.rect(0, 490, 900, 10);
      ctx.fillStyle = "green";
      ctx.fill();

      //PLayer movement:
      if (keys["up"] && !keys["right"] && !keys["left"]) {
        y_new -= speed;
      } else if (keys["right"] && !keys["up"]) {
        x_new += speed;
      } else if (keys["left"] && !keys["up"]) {
        x_new -= speed;
      } else if (keys["up"] && keys["right"]) {
        y_new -= speed;
        x_new += speed;
      } else if (keys["up"] && keys["left"]) {
        y_new -= speed;
        x_new -= speed;
      }

      if (y_new < 440 && isJumping == false && isColliding == false) {
        y_new += speed;
      }

      //Platforms:
      platform1 = new Platform(plat1X, 350, 200, 10, true);
      platformArray.push(platform1);

      platform2 = new Platform(300, 200, 200, 10, false);
      platformArray.push(platform2);

      platform3 = new Platform(400, 300, 200, 10, false);
      platformArray.push(platform3);

      //Platform intersections:
      platformArray.forEach(function(platform) {
        if (boundsIntersect(x_new, y_new, platform.getX, platform.getY) && isJumping == false) {
          isColliding = true;
          y_new -= 0.5;
        } else if (boundsIntersect(x_new, y_new, platform.getX, platform.getY) && isJumping == true) {
          isJumping = false;
          y_new += 11;
          isColliding = true;
        } else {
          isColliding = false;
        }
      });

      var platSpeed = 2;

      //Move platforms:
      platformArray.forEach(function(platform) {
        if (platform.getMoveable) {
          if (platform.getX > 0 && platform.getX < 400) {
            plat1X += 1;
          } else if (platform.getX > 0 && platform.getX > 400) {
            plat1X -= 1
          }
        }
      });

      ctx.save();
      ctx.restore();
    }

    window.requestAnimationFrame(update);
  </script>

</body>

</html>

发生的事情是平台移动的视觉效果正在起作用,但是留下了一条我无法通过的足迹。我知道它一定与我没有删除它有关,但是我不知道JavaScript的细节。

2 个答案:

答案 0 :(得分:0)

玩家卡在“线索”中的原因是,每次调用您的update()函数时,它将3个新的Platform对象(其中1个具有更新的位置)推入{ {1}}。旧的platformArray对象会一直保留在那里,因此,每当您检查与Platform的碰撞时,便会检查与您创建的每个platformArray的碰撞,所以这就是'trail '来自。

我已对您的代码进行了一些更正,以尽量减少入侵。请注意,三个Platform仅创建一次,并在每个Platform上重新呈现。您还会注意到,碰撞仍然无法正常进行,但这是另一回事了(也许update()值得检查)。

boundsIntersect()

答案 1 :(得分:0)

草率,但是我可以通过玩一些更多的东西来得到一个工作版本,这受到先前答案的启发:

<!DOCTYPE html>
<html>
<body>

<style>

canvas{
  background: #eee;
}

</style>

<canvas id="ctx" tabindex=0 width=900 height=500 style="border:1px solid #000000;" onkeypress="movePlayer(event)" onkeyup="keyUp(event)"></canvas>

<script>
var canvas = document.getElementById("ctx");
var ctx = canvas.getContext("2d");
canvas.setAttribute('tabindex', 0);
canvas.focus();
canvas.addEventListener("keydown", movePlayer);

//Maybe I can get a class working?

class Platform {
  constructor(x, y, xS, yS, moveBool) {
    this.xPos = x;
    this.yPos = y;
    this.xSize = xS;
    this.ySize = yS;

    this.moveable = moveBool;
  }

  render() {
   ctx.save()
   ctx.fillStyle = "red";
   ctx.fillRect(this.xPos, this.yPos, this.xSize, this.ySize);
   ctx.restore()
 }

  get getX() {
    return this.xPos;
  }
  get getY() {
    return this.yPos;
  }
  get getxSize() {
    return this.xSize;
  }
  get getySize() {
    return this.ySize;
  }
  get getMoveable() {
    return this.moveable;
  }
}

//Platform array:
var platformArray = [];

//Vars:

var x_new = 50;
var y_new = 50;

var isJumping = false;
var isColliding = false;

var speed = 10;

//Moving platform vars:
var plat1X = 0;
var direction = '';

var keys = {
    up: false,
    right: false,
    left: false
};

function movePlayer(event) {
    switch(event.keyCode){
      //Right key down:
      case 39:
        keys["right"] = true;
        break;
      //Left key down:
      case 37:
        keys["left"] = true;
        break;
      //Up key down:
      case 38:
        keys["up"] = true;
        isJumping = true;
        break;
    }
}

function keyUp(event){
  switch(event.keyCode){
    //Up key up:
    case 38:
      isJumping = false;
      keys["up"] = false;
      break;
    //Right key up:
    case 39:
      keys["right"] = false;
      break;
    //Left key up:
    case 37:
      keys["left"] = false;
      break;
  }

}

function boundsIntersect(x1,y1,x2,y2){
  if(x1 > x2-50 && x1 < x2+200 && y1 < y2 && y1 > y2-55){
    return true;
  }
  return false;
}

function update(){

  window.requestAnimationFrame(update);
  ctx.clearRect(0,0,900,500);
  ctx.fillStyle = "black";
  ctx.beginPath();
  ctx.fillRect(x_new,y_new,50,50);
  //Draw ground:
  ctx.beginPath();
  ctx.rect(0,490,900,10);
  ctx.fillStyle = "green";
  ctx.fill();

  //PLayer movement:
  if(keys["up"] && !keys["right"] && !keys["left"]){
    y_new-=speed;
  } else if(keys["right"] && !keys["up"]){
    x_new+=speed;
  } else if(keys["left"] && !keys["up"]){
    x_new-=speed;
  } else if(keys["up"] && keys["right"]){
    y_new-=speed;
    x_new+=speed;
  } else if(keys["up"] && keys["left"]){
    y_new-=speed;
    x_new-=speed;
  }

  //Gravity
  if(y_new < 440 && isJumping == false && isColliding == false){
    y_new+=speed;
  }

  platformArray = [];

  //Platforms:
  platform1 = new Platform(plat1X,350,200,10, true);
  platformArray.push(platform1);

  platform2 = new Platform(300,200,200,10, false);
  platformArray.push(platform2);

  platform3 = new Platform(400,300,200,10, false);
  platformArray.push(platform3);

  //Move platforms:
  platformArray.forEach(function(platform) {
    if (platform.getMoveable) {
      if (platform.getX >= 400) {
        direction = 'left'
      } else if (platform.getX <= 0) {
        direction = 'right';
        plat1X += 1;
      }

      if(platform.getX > 0 && platform.getY < 400){
        if (direction == 'right') {
          plat1X += 10;
        } else if(direction == 'left'){
          plat1X -= 10;
        }
      }
    }
  });

  // render platforms
   platformArray.forEach(function (platform) {
     platform.render()
   });

  //Platform intersections:
  platformArray.forEach(function(platform){
    if(boundsIntersect(x_new,y_new,platform.getX, platform.getY) && isJumping == false){
      isColliding = true;
      y_new -= 10;
    } else if(boundsIntersect(x_new,y_new,platform.getX, platform.getY) && isJumping == true){
      isJumping = false;
      y_new += 50;
      isColliding = true;
    } else {
      isColliding = false;
    }
  });
}

window.requestAnimationFrame(update);

</script>

</body>
</html>