Javascript 如何在游戏中自动移动我的车
我正在用html 5和canvas开发一款游戏,这是游戏开发的新手。现在我开发了一款游戏,游戏中几乎没有汽车和怪物,我可以通过以下代码控制汽车:Javascript 如何在游戏中自动移动我的车,javascript,html,canvas,Javascript,Html,Canvas,我正在用html 5和canvas开发一款游戏,这是游戏开发的新手。现在我开发了一款游戏,游戏中几乎没有汽车和怪物,我可以通过以下代码控制汽车: update(){ if (keys.ArrowUp) { // Player holding up this.y -= this.speed * frameTime; this.dir = Math.PI * 0; // set direction } i
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();
}
}
update(){
如果(keys.ArrowUp){//玩家举起
this.y-=this.speed*帧时间;
this.dir=Math.PI*0;//设置方向
}
如果(键。箭头向下){//玩家按住
this.y+=this.speed*帧时间;
this.dir=Math.PI*1;//设置方向
}
如果(键。箭头左){//玩家按住左键
this.x-=this.speed*帧时间;
this.dir=Math.PI*1.5;//设置方向
}
如果(键。箭头右){//玩家右握
this.x+=this.speed*帧时间;
this.dir=Math.PI*0.5;//设置方向
}
如果(数学符号)(此速度)=-1){//filp第二辆车的方向
this.dir+=Math.PI;//设置方向
}
怪物.array.forEach(怪物=>{
如果(怪物。我触摸(这个)){
monster.reset();
MonstersGaught+=1;
}
});
如果(this.x>=canvas.width | this.y>=canvas.height | | this.y<0 | | this.x<0){
这是reset();
}
}
但现在我想让汽车自己向不同的方向移动,我不想实现任何路由路径或任何人工智能。我只是想让汽车自己向不同的方向移动。例如,直线移动3秒,然后向右移动2秒,向下移动3秒等等。这是我的工作
感谢您的帮助。您就快到了
只需在update()
方法中添加一个参数,即可编程控制汽车,而不必使用键盘。使其更新(dir)
然后在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')
查看更新过的笔了解详细信息:你的意思是,你想移动其他汽车还是用户的汽车?画布上的汽车。它基本上实现了游戏的自动化。你可以使用setInterval()
耶很有魅力,谢谢你的宝贵解释
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;
}