Samuel D.

asked • 04/14/24

Coding Error where "Cannot read properties of undefined (reading 'x') / (reading 'width')"

Note: This is in Khan Academy's coding environment.


This is the link to my project:

https://www.khanacademy.org/computer-programming/test-dino/6627282749407232


I received the error saying:

Cannot read properties of undefined (reading 'x')

Cannot read properties of undefined (reading 'width')


I was told that the value of dino is undefined, and undefined has no property called x.



How should my code be fixed, and where?


1 Expert Answer

By:

Samuel D.

So, I should find where dino.x or dino.width is being used before the setup function? I moved preload() to after setup() and still got the same error. I don't see where dino.x or dino.width are being called before setup(), unless it is in one of the variables I set up. var dino; var obstacles = []; var obstacleSpeed = 5; var jumpForce = -15; var gravity = 0.6; var isJumping = false; var score = 0; var dinoImg; // Declare variable for dinosaur image var cactusImg; // Declare variable for cactus image function setup() { size(400, 400, P2D); // Set the canvas size dino = { x: 50, y: height - 50, speed: 0 }; // Initialize 'dino' inside 'setup' function } function preload() { // Load pixelated images for the dinosaur and cacti dinoImg = loadImage('dinosaur.png'); cactusImg = loadImage('cactus.png'); }
Report

04/16/24

Mark R.

tutor
Well, you have two different errors here. One has to do with dino not being defined -- that's the error "Cannot read properties of undefined (reading 'x')". Fixing that by either just declaring var dino = { x: 50, y: height - 50, speed: 0 }; or by calling setup() early is fine. But then you get an error: Cannot read properties of undefined (reading 'width') Notice that width is never accessed off of dino (I don't see you actually have dino.width anywhere). It's always being used as a global variable (not as a property of an object). And I notice there are lots of comments saying that width is a global variable. Now, normally, outside of Khan Academy's sandbox, width would not be a global variable. But it looks like it's meant to be in their special environment/sandbox they're providing for you that's using ProcessingJS. I see that in their documentation: https://www.khanacademy.org/computer-programming/width/5933816543707136 But obviously, that's not working in the specific environment hosting the program you're linking to for this question. I don't know really anything about Khan Academy's sandbox. You're probably better off asking in their forums or on StackOverflow (I notice there's a khan-academy tag there).
Report

04/16/24

Still looking for help? Get the right answer, fast.

Ask a question for free

Get a free answer to a quick problem.
Most questions answered within 4 hours.

OR

Find an Online Tutor Now

Choose an expert and meet online. No packages or subscriptions, pay only for the time you need.