You need to enable JavaScript to run this app. 编写平台跳跃游戏碰撞功能遇Cannot set property 'collision' of undefined报错如何修复
优惠活动
大模型
产品
解决方案
定价
更多

编写平台跳跃游戏碰撞功能遇Cannot set property 'collision' of undefined报错如何修复

报错原因

你尝试为存储平台实例的普通数组platforms添加prototype属性,而普通对象的prototype属性默认是undefined,因此为其添加collision属性时会抛出该错误。原型方法需要挂载到平台的构造函数newPlatform上,才能被所有平台实例继承调用。

除此之外你的代码还存在两处隐患:

  • 构造函数newPlatform中height属性未赋值,后续碰撞计算会得到错误结果
  • 构造函数内部属性赋值使用了逗号表达式,可读性差,也存在语法风险

修复方案

  1. 将碰撞方法挂载到newPlatform的原型上,而非数组platforms的原型
  2. 补全newPlatform构造函数中height属性的赋值
  3. 调整构造函数内部的属性赋值语法为常规写法

修复后完整代码

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.17 02:15:03