gpt4 book ai didi

javascript - 如何让玩家锁定其半径内的一个敌人?

转载 作者:行者123 更新时间:2023-12-03 06:57:42 27 4
gpt4 key购买 nike

我已经设置了一个塔防游戏并获得了它,这样你就可以放下塔,敌人就会向你袭来。但是,塔楼正在对其半径内的所有怪物造成伤害。我希望塔楼只对其周围的一个敌人造成伤害。

我设置了两个变量:monsterList 和 towerList。它们都是对象,我已经将其设置为在特定事件时,它将向指定变量添加敌人或塔。因此,当您选择一个空白区域来放置塔时,它会向列表中添加一个对象变量。当您单击下一个级别时也会发生这种情况,但它会创建可以在路径中移动的动态怪物。它看起来有点像这样:

//the variables
var monsterList = {};
var towerList = {};

//how towers or enemies are added
var Monster = {
x:10,
y:10,
type:"Red",
id:Math.random()
}
monsterList[Monster.id] = Monster;

所以,这就是我创建怪物的方式,同样的方式,但有不同的参数,对于一座塔来说。当怪物沿着路径进入塔的范围内时,塔将攻击其范围内的所有怪物。我希望它只锁定其范围内的 1 个怪物。以下是我的碰撞设置方法:

//loops through all the monsters and towers and tests if any of them are
//colliding. If they are colliding, it will decrease the monster's health by
//1/30 of the tower's damage. This is because I have an interval looping
//through this code 30 times a second. So, it deals the damage per second.
for(var key in monsterList){

for(var i in towerList){

if( Collision(towerList[i], monsterList[key]) ){
monsterList[key].health -= ( towerList[i].damage/30 );
}

if( monsterList[key].health <= 0 ) delete monsterList[key];
}
}
//and this is the Collision() function. It pretty much returns true if the
//monster is within the tower's range which is defined by an argument to the
//tower called radius.
function Collision(tower, monster){
return ((monster.y >= (tower.y - tower.radius*20)) &&
(monster.x >= (tower.x - tower.radius*20)) &&
(monster.y <= (tower.y + tower.height + tower.radius*20)) &&
(monster.x <= (tower.x + tower.width + tower.radius*20)));
}

感谢您的帮助!

最佳答案

你的塔上需要这样的东西:

var tower = {
... //your tower properties
target: null
}

然后在循环中:

for(var key in monsterList){
for(var i in towerList) {

if( !towerList[i].target && Collision(towerList[i], monsterList[key]) ) {
towerList[i].target = key;
monsterList[key].health -= ( towerList[i].damage/30 );
}

if( towerList[i].target ) {
monsterList[towerList[i].target].health -= ( towerList[i].damage/30 );
}

if( monsterList[key].health <= 0 )
delete monsterList[key];
}
}

您还可以以更易读的方式编写循环:

monsterList.forEach(function(monster) {

towerList.forEach(function(tower) {
if (!tower.target && Collision(tower, monster)
tower.target = monster

if (tower.target)
tower.target.health -= tower.damage / 30;

if (tower.target.health <= 0) {
var monsterIndex = monsterList.indexOf(tower.target);
delete monsterList[monsterIndex];
}
});
});

关于javascript - 如何让玩家锁定其半径内的一个敌人?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37199205/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com