开发者问题收集

未捕获的错误:无法读取未定义的属性 x

2021-03-19
1359

我正在使用 matter.js 和 p5.js 制作这款游戏​​,你必须使用弹弓和石头让芒果从树上掉下来。代码看起来有点像这样:

SlingShot.js:

    constructor(bodyAInput, pointBInput) {
        var options = {
            bodyA: bodyAInput,
            pointB: pointBInput,
            stiffness: 0.2,
            length: 20

        }
        this.pointB = pointBInput;

        this.constraint = Matter.Constraint.create(options);
        World.add(world, this.constraint);

    }
    detach() {
        this.constraint.bodyA = null;
    }
    attach(bodyInput) {
        this.constraint.bodyA = bodyInput;
    }
    display() {
        
            var pointA = this.constraint.bodyA.position;
            var pointB = this.pointB;

            line(pointA.x -40 , pointA.y, pointB.x - 40, pointB.y);
            line(pointA.x , pointA.y, pointB.x , pointB.y - 3);
            
      
    }
}

Sketch.js(出现错误的相关部分):


function setup() {
    createCanvas(1300, 600);
    engine = Engine.create();
    world = engine.world;

    mango1 = new mango(1100, 100, 30);
    mango2 = new mango(1000, 150, 30);
    mango3 = new mango(900, 200, 30);
    mango4 = new mango(950, 250, 30);
    mango5 = new mango(1200, 200, 30);


    stoneObj = new Stone(230, 400);
    treeObj = new tree(1050, 580);
    groundObject = new ground(width / 2, 600, width, 20);
    //console.log(SlingShot);
    launcherObject = new SlingShot( stoneObj, { x:230, y: 400 });

    Engine.run(engine);

}

创建 launcherObject 时,它会显示错误,如下所示:

matter.js:7769 Uncaught TypeError: Cannot read property 'x' of undefined
    at Object.Vector.add (matter.js:7769)
    at Object.Constraint.create (matter.js:3597)
    at new SlingShot (slingShot.js:12)
    at setup (sketch.js:32)
    at _setup (p5.js:58811)
    at _runIfPreloadsAreDone (p5.js:58752)
    at p5._decrementPreload (p5.js:58761)
    at Image.img.onload (p5.js:74562)

关键是,为什么它会显示错误?

编辑:这是 stone.js 的代码:

class Stone{
    constructor(x,y){
        var options = {
            isStatic: true
        }
        this.body = Bodies.circle(x,y,10,options);
        World.add(world,this.body);
        this.image = loadImage("images/stone.png");
    }
    display(){
        push ();
        image(this.image,this.body.position.x,this.body.position.y,20,20);
        pop ();
    }
}
2个回答

创建 slingshotstoneobj 是构造函数的第一个参数

171089257

,第一个参数为 BodyAinput 分配给 options.body.bodya ,需要为 body> body 对象。

596239612 P> Stone 不是 body 对象,但它具有 body ,因此需要像这样设置选项: < <代码> 875450518
Charlie Wallace
2021-03-20

问题在于您如何通过新的 SlingShot 类传递和读取 stoneObj。在 SlingShot 类中,您尝试读取 pointA 的属性 x,但该属性未定义,可能是因为 stoneObj 没有按预期返回位置。

尝试记录该部分以查看哪里出了问题。

olawrdhalpme
2021-03-19