(p5js/javascript)尝试将2个对象传入函数时出错:未捕获类型错误:对象未定义
我正在尝试将两个对象传递到一个函数中,以查看它们是否会发生冲突,如果会,则销毁它们。在我添加碰撞功能之前,它是工作的。首先尝试通过从对象调用属性,然后使用访问器再次尝试,但我找不到它有什么问题。在带有错误的行下方指示!都会感激你的帮助。谢谢。
编辑:包含我的完整代码,对象中有一些未使用的变量,这就是我一开始没有包含它的原因
编辑2:尝试在代码前添加复选标记if (typeof this.missile != 'undefined')
,但它只是滞后于游戏...
编辑3:非常困惑,如果导弹列表中没有导弹,collide(missiles[i], enemies[k], i, k);
将不会被调用。它被称为,这意味着名单上有一枚导弹,那么为什么它没有定义?变得绝望...
var missiles;
var hero;
var enemies;
function setup()
{
createCanvas(1024, 512);
hero = new hero(1, 0)
enemies = [];
missiles = [];
}
function draw()
{
background(0);
hero.draw();
enemies.push(new enemy(512, 50, 1));
enemies.push(new enemy(700, 50, 1));
for (var i = 0; i < missiles.length; i++)
{
missiles[i].draw();
}
for (var i = 0; i < enemies.length; i++)
{
enemies[i].draw();
}
for (var i = 0; i < missiles.length; i++)
{
for (var k = 0; k < enemies.length; i++)
{
collide(missiles[i], enemies[k], i, k);
}
}
}
function hero(weaponLevel, wingmanLevel)
{
this.weapon = weaponLevel;
this.firerate = 5000 - (this.weapon - 1) * 50;
this.wingman = wingmanLevel;
this.timer = 0;
this.draw = function()
{
fill(255);
ellipse(mouseX, mouseY, 15);
this.update();
}
this.update = function()
{
if (millis() > this.timer)
{
this.fire();
this.timer = this.timer + 500;
}
}
this.fire = function()
{
missiles.push(new missile(mouseX, mouseY, this.weapon));
}
}
function missile(x, y, weaponLevel)
{
this.x = x;
this.y = y - 5;
this.speed = 5;
this.update = function()
{
this.y -= this.speed;
if (this.y + 5 < 0)
{
var i = missiles.indexOf(this);
missiles.splice(i, 1);
}
}
this.draw = function()
{
this.update();
stroke(255);
line(this.x, this.y, this.x, this.y + 5);
}
this.getX = function()
{
return this.x;
}
this.getY = function()
{
return this.y;
}
}
function enemy(x, y, level)
{
this.x = x;
this.y = y;
this.health = level * 10 + 100;
this.currentX = x;
this.currentY = y;
if (random(0, 100) < 3)
{
if (random(0, 100) < 50)
{
this.dropsUpgrade = true;
this.dropsWingman = false;
}
else
{
this.dropsUpgrade = false;
this.dropsWingman = true;
}
}
this.draw = function()
{
rectMode(CENTER);
fill(255,0,0);
rect(this.x, this.y, 15, 15);
}
this.getX = function()
{
return this.currentX;
}
this.getY = function()
{
return this.currentY;
}
}
function collide(missile, enemy, i, k)
{
this.missile = missile;
this.enemy = enemy;
this.xDist = dist(this.missile.getX(), this.enemy.getX()); //Uncaught TypeError: this.missile is undefined
this.yDist = dist(this.missile.getY(), this.enemy.getY());
if (xDist < 15 && yDist < 15)
{
missiles.splice(i, 1);
enemies.splice(k, 1);
}
}
解决方案
收到...
- for循环变量错误(内部for循环使用i而不是k)
- dist函数使用不正确
相关文章