encountering an issue "Error in p5practice.js:97 - Uncaught TypeError: Unable to access property 'y' of undefined"

While working on the paddle section of my code and resolving other errors, I encountered a new issue. After fixing the previous errors, I received the following error message: "p5practice.js:97 Uncaught TypeError: Cannot read property 'y' of undefined." Additionally, I'm struggling to make my paddle function properly even after reviewing multiple pong-like examples.

//variables
var canvas;
var ctx;
var w;
var h;
var ball;
var paddle;
var score1;


//ball object
var BALL = function(x, y) {
    this.x = x;
    this.y = y;
    this.color = "white";
    this.radius = 12;
    this.vx = 3;
    this.vy = -3;
};

//paddle 1
var PADDLE = function(x, y) {
    this.x = 10;
    this.y = h/2 - 50;
    this.color = "white";
    this.width = 5;
    this.height = 100;
    
};

window.addEventListener("keydown", movePaddle);
//keydown event

    //down
function movePaddle(e) {
 
        switch (event.keyCode){
          case 38: //up 
          console.log(paddle.y)
          if (paddle.y - 30 >= -10) {
            paddle.y -= 30;
          }
          break;
          case 40: // down 
          console.log(paddle.y)
          if (paddle.y + 30 < 305) {
            paddle.y += 30;
          }
          break;
        }
      }
     

//DOM load
window.onload = function() {
    canvas = document.getElementById('canvas');
    w = canvas.width;
    h = canvas.height;
    ctx = canvas.getContext('2d');
    ball = new BALL (w/2, h/2);
    paddle = new PADDLE(w-100, h/2);
    drawScore();
    startGame();
    movePaddle(); 
canvas {
border: 3px solid yellow;
background-color: black;
}
<!doctype html>
<html>
    <head>
        <title>Pong</title>
        <script src="p5practice.js"></script>
        <link rel= 'stylesheet' href="p5practice.css">
    </head>
    <body>
        <canvas id="canvas" width="600" height="400"></canvas>
        </script>
    </body>
</html>

Answer №1

To resolve the issue where ball is being initialized after your if statements at the bottom, you should move those statements into the onload or startGame function.

Additionally, make sure to address the handling of variable x by moving it accordingly:

var leftScore = this.x > 10;

//variables
var canvas;
var ctx;
var w;
var h;
var ball;
var paddle;
var score1;


//ball object
var BALL = function(x, y) {
  this.x = x;
  this.y = y;
  this.color = "white";
  this.radius = 12;
  this.vx = 3;
  this.vy = -3;
};

//paddle 1
var PADDLE = function(x, y) {
  this.x = 10;
  this.y = h / 2 - 50;
  this.color = "white";
  this.width = 5;
  this.height = 100;

};

window.addEventListener("keydown", movePaddle);
//keydown event

//down
function movePaddle(e) {

  switch (event.keyCode) {
    case 38: //up 
      console.log(paddle.y)
      if (paddle.y - 30 >= -10) {
        paddle.y -= 30;
      }
      break;
    case 40: // down 
      console.log(paddle.y)
      if (paddle.y + 30 < 305) {
        paddle.y += 30;
      }
      break;
  }
}


//DOM load
window.onload = function() {
  canvas = document.getElementById('canvas');
  w = canvas.width;
  h = canvas.height;
  ctx = canvas.getContext('2d');
  ball = new BALL(w / 2, h / 2);
  paddle = new PADDLE(w - 100, h / 2);
  drawScore();
  startGame();
  movePaddle();

  //bottom
  if (ball.y >= 390) {
    ball.vy = -ball.vy;
    console.log("bottom hit");
  }
  //top
  if (ball.y <= 10) {
    ball.vy = -ball.vy;
    console.log("top hit");
  }

  //right
  if (ball.x >= 590) {
    ball.vx = -ball.vx;
    console.log("right hit");
  }
  //left
  if (ball.x <= 10) {
    score++;
    ball.x = w / 2;
    ball.y = h / 2;
    console.log("left hit");
  }

  //collision with paddle
  if (ball.x < 15) {
    if (ball.y > paddle.y && ball.y < paddle.y + paddle.height) {
      ball.vy = -ball.vy;
      console.log("paddle");
    }
  }
};

function startGame() {
  requestAnimationFrame(startGame);
  ctx.clearRect(0, 0, w, h);
  ball.x += ball.vx;
  ball.y += ball.vy;

  ctx.fillStyle = ball.color;
  ctx.beginPath();
  ctx.arc(ball.x, ball.y, ball.radius, 0, 2 * Math.PI, true);
  ctx.closePath();
  ctx.save();
  ctx.fill();
  ctx.restore();
  ctx.fillStyle = paddle.color;
  ctx.beginPath();
  ctx.save();
  ctx.shadowBlur = 20;
  ctx.shadowOffsetX = 4;
  ctx.shadowOffsetY = 4;
  ctx.shadowColor = "red";
  ctx.fillRect(paddle.x, paddle.y, paddle.width, paddle.height);
  ctx.closePath();
  ctx.restore();
}
//collision with walls
//https://www.khanacademy.org/computer-programming/paddle-ball/830543654



//reset
//https://bl.ocks.org/ruffrey/1e242222aebbcd102a53

//not finished
function reset() {
  ball.x;
  ball.y;
}

//score
var score = 0;

function drawScore() {
  ctx.font = "16px Arial";
  ctx.fillStyle = "#0095DD";
  ctx.fillText("Score: " + score, w / 2, 20);

  var leftScore = this.x > 10;
  if (leftScore) {
    playerCount.score++;
  }
  this.reset();
}
canvas {
  border: 3px solid yellow;
  background-color: black;
}
<!doctype html>
<html>

<head>
  <title>Pong</title>
  <script src="p5practice.js"></script>
  <link rel='stylesheet' href="p5practice.css">
</head>

<body>
  <canvas id="canvas" width="600" height="400"></canvas>
  </script>
</body>

</html>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it possible to assign default values to optional properties in JavaScript?

Here is an example to consider: interface Parameters { label: string; quantity?: number; } const defaultSettings = { label: 'Example', quantity: 10, }; function setup({ label, quantity }: Parameters = { ...defaultSettings }) { ...

Tips for incorporating external JavaScript code into React components

I have been tasked with integrating a graphical widget into a React component for a project I am working on. The widget_api code provided by RIPE Stat is required to accomplish this. Previously, in HTML5, the integration was successful using the following ...

JavaScript encountered a ReferenceError: 'a' has not been declared

One interesting feature of my slider is that it uses links like <a id="foo" class="oslide">Chineese Food</a> to navigate through the slides. To make this navigation function properly, I had to include a.href = "#"; in the link's click even ...

Providing secure access to Apostrophe-CMS S3 assets and attachments via HTTPS

Currently, I am utilizing Amazon S3 to deliver both my static assets and user uploads within the context of apostrophe-cms. While my site is loading via https, all of my assets appear to be loading using http. I have set up a cloudfront distribution at th ...

Is there a way to recognize each individual browser window that is presently open?

Is there a way to uniquely distinguish each separate browser window that is currently open across all major browsers using JavaScript? Let's examine the following scenario: I currently have 3 browser windows open, each with multiple tabs, in a modern ...

Tips for including MUI icon within a list displayed on a map:

Initially, I brought in the AccountCircle Icon from MUI: import { AccountCircle } from '@mui/icons-material'; Then, I utilized styled to customize the icon: const UserIcon = styled(AccountCircle)({ margin: '0px 0px 0px 0px', }); My ex ...

Is there a way to make the console output more visually appealing with some styling?

What techniques do programs such as npm and firebase use to generate visually appealing and informative console output during command execution? Consider the following examples: $ firebase deploy or $ npm i <some-package> ...

Link AngularJS service array length property to the controller's scope through binding

I am attempting to connect the length of an array from another service to my controller's scope in the following manner: app.controller('TestCtrl', function ($scope, safePostService) { $scope.count = safePostService.queue.length; $ ...

Updating a property value within a JSON object: Adjusting attributes in a JSON data format

How can I modify a specific key's value in a JSON array like the following example: input = [{"201708":10,"201709": 12, "metric":"attritionManaged"},{"201708":10,"201709": 12, "metric":"attritionUnManaged"},{"201708":10,"201709": 12, "metric":"EHC"}] ...

Tips for avoiding automatic updates to .js scripts after pressing F5

Is there a method to stop a JavaScript script from resetting when the user refreshes the page? For instance, if I have a picture slider that is constantly changing images, I would like the script to continue where it left off instead of starting over wit ...

The Angular template driven forms are flagging as invalid despite the regExp being a match

My input looks like this: <div class="form-group"> <label for="power">Hero Power</label> <input [(ngModel)]="model.powerNumber" name="powerNumber" type="text" class="form-control" pattern="^[0-9]+$"id= ...

The presence of decimal values within an AJAX URL

Struggling to pass decimal values in an AJAX request to a server-side endpoint. Everything runs smoothly except when trying to include a decimal value in the URL. The "." character is recognized as reserved within the URL schema, causing a 404 error. Seeki ...

Retrieve the inner object contained within a JSON file

I have encountered an issue while trying to parse a specific json format on android. The json structure is as follows: {"header": { "param": "param" }, "body": { "param": "1", "param2": "2", "param3": [ ...

Ways to insert a hyperlink within a div element

Consider the following HTML structure: <article id="1919"> <div class="entry-content clearfix"> <div></div> <div></div> </div> </article> &l ...

I'm curious if it's possible to utilize Raspberry Pi GPIO pins within a JavaScript frontend

Is it possible to utilize Raspberry Pi's GPIO pins in Javascript? Specifically, I am interested in reading the values of the Raspberry Pi PIR sensor without having separate Python and Javascript applications. Ideally, I would like a solution that inte ...

How can you conceal an HTML element when the user is using an iOS device?

I need the code to determine if a user is using an iOS device and, if not, hide the HTML input type "Play" button. So, I'm uncertain whether my iOS detection is correct, the hiding of the "Play" button in the code, or both: <!DOCTYPE html> < ...

The issue arises when using IE8/9 with $.get and .html() functions, as the retrieved data

Below is a snippet of JavaScript code that I am currently working with: $(".refresh").on("click touch", function () { $.get($("a.suggest-date").attr('href') + '#suggestedDate', null, function (result) { console.log(result); ...

Guide on implementing EdgesHelper with imported Collada model using three.js

Having some issues while using the EdgesHelper on a loaded Collada model in three.js: Applying edges to the entire model geometry, Misalignment and scale discrepancies between the Collada model and the generated edges. View Demo var controls, scene, ca ...

Python on the server side generating a downloadable zip file

After passing a parameter from my client to a python script on the server through a GET request, the script initiates a process that results in the creation of a zip file. However, upon making an AJAX call in my client-side JavaScript, I am only able to co ...

I'm having trouble with my Selenium as it doesn't seem to be able to open

Hey there, I've been working on a script to login to Gmail, but I'm having trouble with entering the password after entering the email. public static void main(String[] args) throws Exception { System.setProperty("webdriver.chrome.driver", "E:&b ...