2017-04-19 37 views
1

我正在开发一款游戏,使用html 5和canvas,并且是游戏开发的新产品。现在我开发了一款游戏,其中有很少的汽车,并且有很少的怪物在那里,我可以控制汽车通过下面的代码:如何在游戏中自动移动我的汽车

update(){ 
     if (keys.ArrowUp) { // Player holding up 
      this.y -= this.speed * frameTime; 
      this.dir = Math.PI * 0; // set direction 
     } 
     if (keys.ArrowDown) { // Player holding down 
      this.y += this.speed * frameTime; 
      this.dir = Math.PI * 1; // set direction 
      } 
      if (keys.ArrowLeft) { // Player holding left 
      this.x -= this.speed * frameTime; 
      this.dir = Math.PI * 1.5; // set direction 
     } 
     if (keys.ArrowRight) { // Player holding right 
      this.x += this.speed * frameTime; 
      this.dir = Math.PI * 0.5; // set direction 
     }   
     if(Math.sign(this.speed) === -1){ // filp directio of second car 
      this.dir += Math.PI; // set direction 
     } 

     monsters.array.forEach(monster => { 
      if(monster.isTouching(this)){ 
       monster.reset(); 
       monstersCaught += 1; 
      } 
     }); 
     if (this.x >= canvas.width || this.y >= canvas.height || this. y < 0 || this.x < 0) { 
      this.reset(); 
     } 
    } 

,但现在我想使汽车通过自己在不同directions.I移动不想实现任何路由或者任何AI。我只是想让汽车在不同的方向上自己移动。例如,直线移动3秒,然后右移2秒,下移3秒,等等。这是我的工作pen

任何帮助表示赞赏。

+1

你的意思,你要移动的其他车辆,或用户的车? – nycynik

+0

在帆布的汽车。它基本上是自动化游戏 – RKR

+0

你可以使用'setInterval()' – 2017-04-19 00:49:12

回答

2

你几乎在那里!

只需在update()方法中添加一个参数即可,而不是使用键盘来编程控制您的汽车。让它update(dir)

if (!dir && keys.ArrowUp) dir = 'up' // Player holding up 
if (dir === 'up') { 
     this.y -= this.speed * frameTime; 
     this.dir = Math.PI * 0; // set direction 
} 

然后在updateObjects(),与你的新的更新功能与方向

heros.array[2].update('left'); 

打电话给你的汽车的汽车现在这款车将继续向左移动!

汽车改变方向怎么样?

您可以保留一个内部值来跟踪汽车在同一方向行驶多久,以及它驾驶的方向。当它符合您设置的距离/时间max时,让它选择一个新的方向,同时重置跟踪器值!

this.traveled = 0; 
this.currentDirection = 'left'; 
.... 
this.traveled += distance; // update the tracker 
.... 
if(this.traveled > 1000) { // wow we already traveled 1000px to the left, time to switch direction! 
    this.currentDirection = 'right'; 
    this.traveled = 0; 
} 

结帐更新的笔.update('left').update('random')的细节:https://codepen.io/xna2/project/editor/XjQnqZ/

+0

是啊作品像一个魅力和感谢宝贵的解释 – RKR