编写平台跳跃游戏碰撞功能遇Cannot set property 'collision' of undefined报错如何修复
报错原因
你尝试为存储平台实例的普通数组platforms添加prototype属性,而普通对象的prototype属性默认是undefined,因此为其添加collision属性时会抛出该错误。原型方法需要挂载到平台的构造函数newPlatform上,才能被所有平台实例继承调用。
除此之外你的代码还存在两处隐患:
- 构造函数
newPlatform中height属性未赋值,后续碰撞计算会得到错误结果 - 构造函数内部属性赋值使用了逗号表达式,可读性差,也存在语法风险
修复方案
- 将碰撞方法挂载到
newPlatform的原型上,而非数组platforms的原型 - 补全
newPlatform构造函数中height属性的赋值 - 调整构造函数内部的属性赋值语法为常规写法
修复后完整代码
const platforms = []; var newPlatform = function(x, y) { this.x = x; this.y = y; this.width = 50; this.height = 20; // 可根据需求调整高度值,也可改为参数传入 } var platform1 = new newPlatform(10, 100); var platform2 = new newPlatform(50, 50); platforms.push(platform1); platforms.push(platform2); var player = { x:100, y:305, width:80, height:120, velocity_y:4 } // 为平台构造函数原型添加碰撞方法 newPlatform.prototype.collision = function(player) { return (this.x < player.x + player.width && this.x + this.width > player.x && this.y < player.y + player.height && this.y + this.height > player.y); } for (let i = 0; i < platforms.length; i++) { if (platforms[i].collision(player)) { player.velocity_y = 0; } }
内容的提问来源于stack exchange,提问作者Prograbit
相关产品推荐
相关产品推荐

