JavaScript What do the x and y values mean here? Can you show in a figure?

  • Thread starter Thread starter shivajikobardan
  • Start date Start date
  • Tags Tags
    Figure Mean
AI Thread Summary
The discussion centers on a JavaScript function, checkBoundaryCollision, designed to detect and respond to boundary collisions for a ball moving within a canvas. The function checks if the ball's position exceeds the canvas dimensions and reverses its direction accordingly. There are recommendations for using parentheses to enhance code clarity, although some participants argue that they may not be necessary due to operator precedence rules in JavaScript. The conversation also touches on the importance of defining variables used in the function, suggesting that users should refer to other parts of the code for variable definitions. Additionally, a more complex implementation using arrays for ball properties and a CheckWalls function is introduced, which includes logic for handling the ball's position and radius more dynamically. The use of setInterval for animation is critiqued, with a preference expressed for requestAnimationFrame as a more efficient method for animations in JavaScript.
shivajikobardan
Messages
637
Reaction score
54
TL;DR Summary
HTML5 canvas javascript
JavaScript:
function checkBoundaryCollision() {

  if (x - ballRadius <= 0 || x + ballRadius >= canvasWidth) {

    dx = -dx;

  }

  if (y - ballRadius <= 0 || y + ballRadius >= canvasHeight) {

    dy = -dy;

  }

}

A5gv62pzDoiMQslngM79oB_Hgmk3H9r2Sk5yoMTIcnPHPvE1Xg.png


Full code here:
 
Technology news on Phys.org
x and y are the current positions of the ball.
x ranges from 0 (far left) to canvasWidth.
y ranges from 0 to canvasHeight.
dx and dy and the x and y increments - so on each cycle you would execute x=x+dx; y=y+dy;

I also recommend the use of parenthesis as follows:
Code:
function checkBoundaryCollision() {
  if ( ((x - ballRadius) <= 0) || ((x + ballRadius) >= canvasWidth)) {
    dx = -dx;
  }
  if ( ((y - ballRadius) <= 0) || ((y + ballRadius) >= canvasHeight)) {
    dy = -dy;
  }
}
 
.Scott said:
x and y are the current positions of the ball.
x ranges from 0 (far left) to canvasWidth.
y ranges from 0 to canvasHeight.
dx and dy and the x and y increments - so on each cycle you would execute x=x+dx; y=y+dy;

Those are reasonable guesses, but it may have been better to tell the OP to look elsewhere in the code for the definitions of these variables, since they aren't defined in the extract they have posted.

Give a man a fish, etc.
 
.Scott said:
I also recommend the use of parenthesis as follows:
Code:
function checkBoundaryCollision() {
  if ( ((x - ballRadius) <= 0) || ((x + ballRadius) >= canvasWidth)) {
    dx = -dx;
  }
  if ( ((y - ballRadius) <= 0) || ((y + ballRadius) >= canvasHeight)) {
    dy = -dy;
  }
}
Nothing wrong with your recommendation, but IMO the following is just as clear. In my version I've written each of the four comparisons such as (x - ballRadius <= 0) without parentheses around these expressions. Since addition and subtraction are of higher precedence in Javascript (and other languages derived from C) than any of the comparison operators, all four comparisons in the code above will be evaluated after the subtractions or additions are performed. See http://www.devdoc.net/web/developer...t=Table Precedence ,( … ) 46 more rows

One could also remove the parentheses around the comparison expressions, since logical AND and logical OR are at considerably lower comparisons, but I've left the parentheses in. My reasoning is that programmers with at least a little experience are aware of the precedence levels of the arithmetic operators vs. the comparison operators, but might not be as aware of how the logical operators fit into the precedence relationships.
JavaScript:
function checkBoundaryCollision() {
  if ( (x - ballRadius <= 0) || (x + ballRadius >= canvasWidth) ) {
    dx = -dx;
  }
  if ( (y - ballRadius <= 0) || (y + ballRadius >= canvasHeight) ) {
    dy = -dy;
  }
}
 
My rule with parentheses is to only put them in where they are needed, otherwise you have to spend time working out what they are doing, only to find that they aren't doing anything. In practice I leave decisions like this up to https://prettier.io/, which takes the same view. In a decent text editor this makes it pretty easy to see what is going on.

1674148854096.png
 
pasmith said:
Those are reasonable guesses, but it may have been better to tell the OP to look elsewhere in the code for the definitions of these variables, since they aren't defined in the extract they have posted.

Give a man a fish, etc.
.. and you'll end up wanting to give him a bigger fish.
Code:
const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");
const ballRadius = 10;

var ballX = Array();
ballX.speed = 2.4;
ballX.vel   = ballX.speed;
ballX.rad   = ballRadius;
ballX.limit = canvas.width;
ballX.pos   = 20;

var ballY = Array();
ballY.speed = 1.7;
ballY.vel   = ballY.speed;
ballY.rad   = ballRadius;
ballY.limit = canvas.height;
ballY.pos   = 20;

function CheckWalls(ball) {
  if(ball.pos<0) {
    ball.pos = -ball.pos;
    ball.vel = ball.speed;
  }
  if(ball.pos>ball.limit) {
    ball.pos = (2*ball.limit)-ball.pos;
    ball.vel = -ball.speed;
  }
  if(ball.pos<ball.rad) {
    ball.erad = (ball.pos+ball.rad)/2;
    ball.epos = ball.erad;
  } else if((ball.limit-ball.pos)<ball.rad) {
    ball.erad = (ball.limit-ball.pos+ball.rad)/2;
    ball.epos = ball.limit-ball.erad;
  } else {
    ball.erad = ball.rad;
    ball.epos = ball.pos;
  };
  return ball;
}

function draw() {
  // Draw the puck
  ctx.beginPath();
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  CheckWalls(ballX);
  CheckWalls(ballY);
  ctx.ellipse(ballX.epos, ballY.epos, ballX.erad, ballY.erad, 0, 0, Math.PI * 2);
  ctx.fillStyle = "red";
  ctx.fill();
  ctx.closePath();
  ballX.pos = ballX.pos + ballX.vel;
  ballY.pos = ballY.pos + ballY.vel;
}
setInterval(draw, 12);
 
.Scott said:
.. and you'll end up wanting to give him a bigger fish.
Yes, particularly as the OP has taken a step backwards with setInterval this time round; his last question used requestAnimationFrame, which is the right way to do animations in JavaScript.
 

Similar threads

Replies
11
Views
2K
Replies
1
Views
1K
Replies
12
Views
2K
Replies
0
Views
312
Replies
4
Views
5K
Replies
1
Views
1K
Back
Top