2016-11-07 39 views
-2

我想製作一個像「mud」這樣的物體,導致玩家的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; 
    } 
}; 

回答

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