如何在我的平台游戏中制作一个减慢玩家速度的对象?

时间:2016-11-07 22:56:55

标签: javascript

我想做一个像#34;泥"这会导致玩家的x和y速度和跳跃速度在他们站立时减慢,我该怎么做?这是我的代码中现在处理播放器速度的部分:

var playerXSpeed = 7;

Player.prototype.moveX = function(step, level, keys) {
  this.speed.x = 0;
  if (keys.left) this.speed.x -= playerXSpeed;
  if (keys.right) this.speed.x += playerXSpeed;

  var motion = new Vector(this.speed.x * step, 0);
  var newPos = this.pos.plus(motion);
  var obstacle = level.obstacleAt(newPos, this.size);

  if (obstacle)
    level.playerTouched(obstacle);
  else
    this.pos = newPos;
};

var gravity = 34;
var jumpSpeed = 15:
var playerYSpeed = 6;

Player.prototype.moveY = function(step, level, keys) {
  // Accelerate player downward (always)
  this.speed.y += step * gravity;;
  var motion = new Vector(0, this.speed.y * step);
  var newPos = this.pos.plus(motion);
  var obstacle = level.obstacleAt(newPos, this.size);
  // The floor is also an obstacle -- only allow players to 
  // jump if they are touching some obstacle.
  if (obstacle) {
    level.playerTouched(obstacle);
    if (keys.up && this.speed.y > 0)
      this.speed.y = -jumpSpeed;
    else
      this.speed.y = 0;
  } else {
    this.pos = newPos;
  }
};

1 个答案:

答案 0 :(得分:0)

我觉得你的问题有点苛刻,不值得你的问题一下子就投了一票。让我试着就这个问题给你一些建议。

看起来你正在从你的运动功能中评估你的障碍逻辑。这违背了让您的职能承担单一责任的最佳做法。我建议重构你的代码,让运动功能只进行“运动”,并对其他地方的障碍进行评估,一个好的地方就是你的更新循环。

我将在这里提供轻量级重构,以说明您如何考虑重新组织代码。我希望你觉得这很有用!

YourGameController.prototype.update = function () {
  this.referenceToYourPlayer.movePlayer(this.keysReference);
  this.referenceToYourLevel.handleCollisions();
}

var gravity = 34;
var jumpSpeed = 15:
var playerYSpeed = 6;
var playerXSpeed = 7;

Player.prototype.movePlayer = function (keys) {
  this.moveX(keys);
  this.moveY();
}

Player.prototype.moveX = function(keys) {
  this.speed.x = 0;
  if (keys.left) this.speed.x -= playerXSpeed;
  if (keys.right) this.speed.x += playerXSpeed;

  var motion = new Vector(this.speed.x * step, 0);
  var newPos = this.pos.plus(motion);
};

Player.prototype.moveY = function() {
  // Accelerate player downward (always)
  this.speed.y += step * gravity;;
  var motion = new Vector(0, this.speed.y * step);
  var newPos = this.pos.plus(motion);
};