不能让玩家成为两个人

时间:2017-05-23 18:28:00

标签: javascript

我正在尝试为javascript游戏添加第二个播放器,但代码不能正常工作。我需要一些关于如何完成这项工作的指示。第二个玩家并不需要花哨,不同的颜色方块就足够了。我现在的球员是绿色广场。任何信息都会有所帮助,谢谢。



T()

var myObstacle;
(function() {
    var requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.msRequestAnimationFrame;
    window.requestAnimationFrame = requestAnimationFrame;
})();
function startGame() {}
var canvas = document.getElementById("canvas"),
    ctx = canvas.getContext("2d"),
    width = 700,
    height =600,
    player = {
      x : 1,
      y : 7,
      width : 25,
      height : 25,
      speed: 10,
      velX: 0,
      velY: 0,
      jumping: false
    },
    keys = [],
    friction = .9,
    gravity = .8;
 
canvas.width = width;
canvas.height = height;

function update(){
  // check keys
    if (keys[38] || keys[32]) {
        // up arrow or space
      if(!player.jumping){
       player.jumping = true;
       player.velY = -player.speed*.1;
      }
    }
    if (keys[39]) {
        // right arrow
        if (player.velX < player.speed) {             
            player.velX++;         
         }     
    }     
    if (keys[37]) {         
        // left arrow         
        if (player.velX > -player.speed) {
            player.velX--;
        }
    }
 
    player.velX *= friction;
 
    player.velY += gravity;
 
    player.x += player.velX;
    player.y += player.velY;
 
    if (player.x >= width-player.width) {
        player.x = width-player.width;
    } else if (player.x <= 0) {         
        player.x = 0;     
    }    
  
    if(player.y >= height-player.height){
        player.y = height - player.height;
        player.jumping = false;
    }
 
  ctx.clearRect(0,0,width,height);
  ctx.fillStyle = "green";
  ctx.fillRect(player.x, player.y, player.width, player.height);
 
  requestAnimationFrame(update);
}
 
document.body.addEventListener("keydown", function(e) {
    keys[e.keyCode] = true;
});
 
document.body.addEventListener("keyup", function(e) {
    keys[e.keyCode] = false;
});
 
window.addEventListener("load",function(){
    update();
});
&#13;
&#13;
&#13;

请尽可能帮助,谢谢。

2 个答案:

答案 0 :(得分:1)

使用一点OOP:

var myObstacle;
(function() {
    var requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.msRequestAnimationFrame;
    window.requestAnimationFrame = requestAnimationFrame;
})();

function Player(color){
  this.x =  1;
  this.y = 7
  this.width = 25
  this.height= 25
  this.speed= 10
  this.velX= 0
  this.velY= 0
  this.jumping= false
  this.color = color;
}

function startGame() {}
var canvas = document.getElementById("canvas"),
    ctx = canvas.getContext("2d"),
    width = 700,
    height =600,
    player = new Player('green'),
    player2 = new Player('red')
    keys = [],
    friction = .9,
    gravity = .8;
 
canvas.width = width;
canvas.height = height;

function update(){
  // check keys
    if (keys[38] || keys[32]) {
        // up arrow or space
      if(!player.jumping){
       player.jumping = true;
       player.velY = -player.speed*.1;
      }
    }
    if (keys[39]) {
        // right arrow
        if (player.velX < player.speed) {             
            player.velX++;         
         }     
    }     
    if (keys[37]) {         
        // left arrow         
        if (player.velX > -player.speed) {
            player.velX--;
        }
    }
 
    player.velX *= friction;
 
    player.velY += gravity;
 
    player.x += player.velX;
    player.y += player.velY;
 
    if (player.x >= width-player.width) {
        player.x = width-player.width;
    } else if (player.x <= 0) {         
        player.x = 0;     
    }    
  
    if(player.y >= height-player.height){
        player.y = height - player.height;
        player.jumping = false;
    }
    
    
    player2.velY += gravity;
 
    player2.x += player2.velX;
    player2.y += player2.velY;
 
    if (player2.x >= width-player2.width) {
        player2.x = width-player2.width;
    } else if (player2.x <= 0) {         
        player2.x = 0;     
    }    
  
    if(player2.y >= height-player2.height){
        player2.y = height - player2.height;
        player2.jumping = false;
    }
 
  ctx.clearRect(0,0,width,height);
  ctx.fillStyle = player.color;
  ctx.fillRect(player.x, player.y, player.width, player.height);
  ctx.fillStyle = player2.color;
  ctx.fillRect(player2.x, player2.y, player2.width, player2.height);
  requestAnimationFrame(update);
}
 
document.body.addEventListener("keydown", function(e) {
    keys[e.keyCode] = true;
});
 
document.body.addEventListener("keyup", function(e) {
    keys[e.keyCode] = false;
});
 
window.addEventListener("load",function(){
    update();
});
<html>
<head>
    <title>Square Stairs™</title>
</head>
<body bgcolor="#000">
 <canvas id="canvas" style="border:3px solid #fff"></canvas>
</body>
</html>

答案 1 :(得分:1)

好吧,我无法抗拒......我添加了更多的OOP。所以,现在你可以添加尽可能多的玩家。重要的区别是颜色和键映射。我的例子(任意)增加了三名球员:

// Find the extension method based on the signature I have defined for the usage
                // public static IEnumerable<RuleDescription> GetRules<T>(this AbstractValidator<T> validator, bool documentNested = false)
                var runtimeMethods = typeof(ValiDoc).GetRuntimeMethods();

                MethodInfo generatedGetRules = null;

                // Nothing fancy for now, just pick the first option as we know it is GetRules
                using (IEnumerator<MethodInfo> enumer = runtimeMethods.GetEnumerator())
                {
                    if (enumer.MoveNext()) generatedGetRules = enumer.Current;
                }

                // Create the generic method instance of GetRules()
                generatedGetRules = generatedGetRules.MakeGenericMethod(childValidator.ValidatorType.GetTypeInfo().BaseType.GenericTypeArguments[0]);

                //Parameter 1 = Derived from AbstractValidator<T>, Parameter 2 = boolean
                var parameterArray = new object[] { childValidator.GetValidator(new PropertyValidatorContext(new ValidationContext(rule.Member.DeclaringType), rule, propertyName)), true };

                //Invoke extension method with validator instance
                var output = generatedGetRules.Invoke(null, parameterArray) as IEnumerable<RuleDescription>;

&#13;
&#13;
var players=[];
players.push(new Player('green', {
   32: 'jump',
   37: 'left',
   38: 'jump',
   39: 'right'
}))
players.push(new Player('red', {
   56: 'jump',
   52: 'left',
   54: 'right'
}, width-25))
players.push(new Player('blue', {
   87: 'jump',
   65: 'left',
   68: 'right'
}, (width-25)/2))
&#13;
var myObstacle;
(function() {
    var requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.msRequestAnimationFrame;
    window.requestAnimationFrame = requestAnimationFrame;
})();
function startGame() {}

function Player(color,keymap,x) {
   this.x = (typeof x === 'undefined') ? 1 : x;
   this.y = 7;
   this.width  = 25;
   this.height = 25;
   this.speed  = 10;
   this.velX   = 0;
   this.velY   = 0;
   this.jumping= false;

   this.keymap = {}
   for (let key in keymap) {
      switch (keymap[key]) {
         case 'jump':
            this.keymap[key] = this.jump
            break;
         case 'left':
            this.keymap[key] = this.moveLeft
            break;
         case 'right':
            this.keymap[key] = this.moveRight
            break;
      }
   }
   this.color  = color;
} // Player()

Player.prototype.jump=function () {
   if (!this.jumping) {
    this.jumping = true;
    this.velY = -this.speed*1.5;
   }
}
Player.prototype.moveRight = function () {
   if (this.velX < this.speed) {
       this.velX++;
    }
}
Player.prototype.moveLeft = function () {
   if (this.velX > -this.speed) {
       this.velX--;
   }
}
// Globals
var canvas = document.getElementById("canvas"),
    ctx = canvas.getContext("2d"),
    width = 700,
    height =600,
    keys = [],
    friction = .9,
    gravity = .8;

canvas.width = width;
canvas.height = height;

// Set up players
var players=[];
players.push(new Player('green', {
   32: 'jump',
   37: 'left',
   38: 'jump',
   39: 'right'
}))
players.push(new Player('red', {
   56: 'jump',
   52: 'left',
   54: 'right'
}, width-25))
players.push(new Player('blue', {
   87: 'jump',
   65: 'left',
   68: 'right'
}, (width-25)/2))

function update() {
   ctx.clearRect(0,0,width,height);
   players.forEach(player => {
      // check player-specific keys
      for (let i in player.keymap)
      {
         if (keys[i] && typeof player.keymap[i] === 'function')
            player.keymap[i].bind(player)();
      }

      player.velX *= friction;

      player.velY += gravity;

      player.x += player.velX;
      player.y += player.velY;

      if (player.x >= width-player.width) {
         player.x = width-player.width;
      } else if (player.x <= 0) {
         player.x = 0;
      }

      if (player.y >= height-player.height) {
         player.y = height - player.height;
         player.jumping = false;
      }

      ctx.fillStyle = player.color;
      ctx.fillRect(player.x, player.y, player.width, player.height);
   }) // player.forEach
   requestAnimationFrame(update);
}

document.body.addEventListener("keydown", function(e) {
//  console.log(e.keyCode);
   keys[e.keyCode] = true;
});

document.body.addEventListener("keyup", function(e) {
   keys[e.keyCode] = false;
});

window.addEventListener("load",function(){
    update();
});
&#13;
&#13;
&#13;