+ 1

Cannot read property 'x' of undefined

Given this.x = player.x, in return cannot read property x of undefined. How to get x from new Bullet()? ctx.fillStyle = " white" for(var i = 0; i < numberOfBullets; i++){ ctx.fillRect(bullets[i].x, bullets[i].y, bullets[i].width, bullets[i].height) bullets[i].shoot() } https://code.sololearn.com/W0vkm7d4c34t/?ref=app

9th Sep 2020, 6:52 AM
Tri Satria [NEW]
Tri Satria [NEW] - avatar
3 Antworten
+ 1
I'm unable to reproduce the problem when I run it now. Did you change the code since posting this question? Aside from the specific question you asked, the following changes seem like improvements to your code: You don't really need an array of bullets that don't move. You just need to maintain the bullets that are actually moving. In other words, numberOfBullets could represent the number of bullets available to shoot while bullets.length can represent the number of bullets on screen and moving. This way, you don't waste time looping through them and moving them close to the player with every update. Your bullet class-like function can look like this: // Create a Bullet only when you're actually shooting it. function Bullet(){ this.x = player.x this.y = player.y this.width = player.width this.height = player.height this.vx = 0 this.vy = 5 this.update = function() { this.y -= this.vy; }; } Your shoot could look like this: function shoot(){ var newBullet = new Bullet(); bullets.push(newBullet); } Your animate can use this modified code: // keep bullets only when they're on the screen. bullets = bullets.filter(function(bullet) { return bullet.y > 0; }); for(var i = 0; i < bullets.length; i++){ ctx.fillRect(bullets[i].x, bullets[i].y, bullets[i].width, bullets[i].height); } and: bullets.forEach(function(bullet) { bullet.update(); }); That update loop could be done as part of your render bullets loop but it looked like you were keeping object updates separate from drawing them. The Bullet update method is similar to your player move processing step so I separated the bullet update to be consistent.
9th Sep 2020, 7:25 PM
Josh Greig
Josh Greig - avatar
0
I see and i think i will be refactoring my code like so when i got the solution. Anyway would you mind to check my newest question. There are several problems you could probably solve related with animation and button events.
10th Sep 2020, 6:03 AM
Tri Satria [NEW]
Tri Satria [NEW] - avatar
0
Your link to code now points at the default template for HTML, CSS, and JS. Where is your newest question? I can see your codes listed in your profile but I can't find your questions.
10th Sep 2020, 8:16 PM
Josh Greig
Josh Greig - avatar