JavaScript Ping Pong Challenge

I'm currently investigating why the browser returns NaN for the Positions. The game is being rendered in a loop and updated as soon as the monitor is ready, which is defined in the update() function and runs infinitely. The reset() function is a part of the update process, so it randomly generates headings. There is also a while loop that filters out small and boring movements.

The Positions consist of:

  1. A direction, which is an Array with x and y coordinates.
  2. A Velocity constant throughout the game.
  3. A Difference value comprising of time delta, indicating how many milliseconds have passed from the last rendered frame to the new one.

I would greatly appreciate your assistance.

//br.js

 

     const ausgebur_Velocity = .002
        class Ball {
            constructor(ballElement) {
                this.ballElement = ballElement
                this.reset()
            }
        
            get x() {
                return parseFloat(getComputedStyle(this.ballElement).getPropertyValue("--x"))
            }
        
            set x(value) {
                this.ballElement.style.setProperty("--x", value)
            }
        
            get y() {
                return parseFloat(getComputedStyle(this.ballElement).getPropertyValue("--y"))
            }
        
            set y(value) {
                this.ballElement.style.setProperty("--y", value)
            }
        
            reset() {
                this.x = 50;
                this.y = 50;
                this.direction = { x: 50, y: 25 }
        
                while (Math.abs(this.direction.x) <= .2 || Math.abs(this.direction.x >= .9)) {
                    const heading = randomNumberBet(0, 2 * Math.PI)
                    this.direction = { x: Math.cos(heading), y: Math.sin(heading) }
        
                }
                this.velocity = ausgebur_Velocity
            }
        
            update(differ) {
                this.x += this.direction.x * this.velocity * differ;
                this.y += this.direction.y * this.velocity * differ;
                console.log(this.x)
                console.log(this.y)
        
            }
        
        }
        
        function randomNumberBet(min, max) {
            return Math.random() * (max - min) + min
        }
        
        
        // Main Script Below
        const ball = new Ball(document.getElementById('ball'))
        
        let lastTime
        function update(time) {
            if (lastTime != null) {
                const differ = time - lastTime
        
                ball.update()
            }
            lastTime = time
        
            window.requestAnimationFrame(update)
        }
        
        window.requestAnimationFrame(update)
        
         
    //style.css
    
        *,
        *::after,
        *::before {
        box-sizing: border-box;
    }
    
    :root {
        --hue: 200;
        --saturation: 50%;
        --foreground: hsl(var(--hue), var(--saturation), 75%);
        --background: hsl(var(--hue), var(--saturation), 25%);
    }
    
    body {
        overflow: hidden;
        margin: 0;
        background-color: var(--background)
    }
    
    .control {
        --position: 50;
    
        position: absolute;
        background-color: var(--foreground);
        top: calc(var(--position)*1vh);
        transform: translateY(-50%);
        width: 1vh;
        height: 10vh;
    }
    
    #player_control {
        left: 1vw;
    }
    
    #pc_control {
        right: 1vw;
    }
    
    #ball {
        --x: 50;
        --y: 50;
    
        position: absolute;
        background-color: var(--foreground);
        left: calc(var(--x)*1vh);
        top: calc(var(--y)*1vh);
        transform: translate(-50%, -50%);
        width: 3vh;
        height: 3vh;
        border-radius: 50%;
    
    }
    
    .score {
        display: flex;
        justify-content: center;
        font-weight: bold;
        font-size: 7vh;
        color: var(--foreground);
    }
    
    .score>* {
        flex-grow: 1;
        flex-basis: 0%;
        padding: 0 2vh;
        margin: 1vh 0;
        opacity: .5;
    }
    
    .score>:first-child {
        text-align: right;
        border-right: .5vh solid var(--foreground);
    }

//ping.html

    <!DOCTYPE html>
    <html lang="en">
    
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <link rel="stylesheet" href="/style.css">
        <script src="/br.js" type="module"></script>
        <title>PING</title>
    </head>
    
    <body>
        <div class="score">
            <div class="player_score">0</div>
            <div class="pc_score">0</div>
        </div>
    
        <div id="ball"></div>
        <div class="control" id="player_control"></div>
        <div class="control" id="pc_control"></div>
    </body>
    
    </html>

Answer №1

Seems like the issue lies in fetching the coordinates from the --x and --y CSS properties, which are not defined here.

Using top and left seems to work better, but it might be necessary to enhance your algorithms.

const ausgebur_Velocity = .002
class Ball {
  constructor(ballElement) {
    this.ballElement = ballElement
    this.reset()
  }

  get x() {
    return parseFloat(getComputedStyle(this.ballElement).getPropertyValue("left"))
  }

  set x(value) {
    this.ballElement.style.setProperty("left", "" + value + "px")
  }

  get y() {
    return parseFloat(getComputedStyle(this.ballElement).getPropertyValue("top"))
  }

  set y(value) {
    this.ballElement.style.setProperty("top", "" + value + "px")
  }

  reset() {
    this.x = 50;
    this.y = 50;
    this.direction = {
      x: 50,
      y: 25
    }

    while (Math.abs(this.direction.x) <= .2 || Math.abs(this.direction.x >= .9)) {
      const heading = randomNumberBet(0, 2 * Math.PI)
      this.direction = {
        x: Math.cos(heading),
        y: Math.sin(heading)
      }

    }
    this.velocity = ausgebur_Velocity
  }

  update(differ) {
    this.x += this.direction.x * this.velocity * differ;
    this.y += this.direction.y * this.velocity * differ;
    console.log("x", this.x)
    console.log("y", this.y)

  }

}

function randomNumberBet(min, max) {
  return Math.random() * (max - min) + min
}


// Main Script Below
const ball = new Ball(document.getElementById('ball'))

let lastTime

function update(time) {
  if (lastTime != null) {
    const differ = time - lastTime
    ball.update(differ)
  }
  lastTime = time

  window.requestAnimationFrame(update)
}

window.requestAnimationFrame(update)
*,
*::after,
*::before {
  box-sizing: border-box;
}

 :root {
  --hue: 200;
  --saturation: 50%;
  --foreground: hsl(var(--hue), var(--saturation), 75%);
  --background: hsl(var(--hue), var(--saturation), 25%);
}

body {
  overflow: hidden;
  margin: 0;
  background-color: var(--background)
}

.control {
  --position: 50;
  position: absolute;
  background-color: var(--foreground);
  top: calc(var(--position)*1vh);
  transform: translateY(-50%);
  width: 1vh;
  height: 10vh;
}

#player_control {
  left: 1vw;
}

#pc_control {
  right: 1vw;
}

#ball {
  --x: 50;
  --y: 50;
  position: absolute;
  background-color: var(--foreground);
  left: calc(var(--x)*1vh);
  top: calc(var(--y)*1vh);
  transform: translate(-50%, -50%);
  width: 3vh;
  height: 3vh;
  border-radius: 50%;
}

.score {
  display: flex;
  justify-content: center;
  font-weight: bold;
  font-size: 7vh;
  color: var(--foreground);
}

.score>* {
  flex-grow: 1;
  flex-basis: 0%;
  padding: 0 2vh;
  margin: 1vh 0;
  opacity: .5;
}

.score>:first-child {
  text-align: right;
  border-right: .5vh solid var(--foreground);
}
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="stylesheet" href="/style.css">
  <script src="/br.js" type="module"></script>
  <title>PING</title>
</head>

<body>
  <div class="score">
    <div class="player_score">0</div>
    <div class="pc_score">0</div>
  </div>

  <div id="ball"></div>
  <div class="control" id="player_control"></div>
  <div class="control" id="pc_control"></div>
</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

Using jQuery AJAX to Populate a Textbox and Dropdown Menu

I am new to using JQuery AJAX, so I am still learning the syntax. Currently, I am retrieving values from a database and populating a dropdown box. What I would like AJAX to do is fill in three other fields with hardcoded information when a selection is mad ...

How to align two <select> elements side by side using Bootstrap

The issue I am encountering is that these two select elements within the same control-group are being displayed vertically when I want them to be displayed horizontally. I attempted using inline-block in CSS, but there are other <div> elements with ...

Significant Google Maps malfunction detected with API V3

Update: Issue resolved, check out my answer below. The scenario: User interacts with a map-image google maps API V3 is loaded using ajax the map is displayed in a dialog window or lightbox What's going on: The map loads and all features are funct ...

Transforming the AngularJS $http GET method to OPTION and including custom headers

var users= $resource('http://myapp.herokuapp.com/users', {}); users.get(); The change in the HTTP GET method to OPTION occurred after implementing a header method. var users= $resource('http://myapp.herokuapp.com/users', {}, { get ...

Utilizing a function within a span element

Can anyone help me figure out what I'm doing wrong while trying to toggle between a span and an input text field using the on function? If you want to take a look, I've created a fiddle for it here User Interface <div> <span >My va ...

Decode my location and input the address before validating it

While I have come across numerous plugins that enable geolocation and display it on a map, I am searching for something unique. I am interested in implementing geocoding when a user visits the page with an option to "allow geolocation." If the user agrees ...

Angular does not alter the focus when a new component is loaded

Currently, I am working on resolving an accessibility issue with a screen reader in an Angular2 web application. When componentA (code shown below as Before) is loaded in Chrome, the entire browser window gains focus and the screen reader narrator announce ...

Basic use of AJAX for sending the value from jQuery's datepicker

As a novice in JavaScript and AJAX, I'm hoping for your patience as I navigate my way through. In the scope of this project, I am utilizing the CodeIgniter framework. My objective is to implement a datepicker and transmit its value via AJAX. Below is ...

Tips for detecting when no checkboxes in a group are selected or when at least one checkbox is selected, and then applying a class to the corresponding div

<div class="accordion-group"> <div class="accordion-heading"> <a href="#collapse" data-parent="#accordionQuiz" data-toggle="collapse1.." class="accordion-toggle"> <strong>1...</strong> Question ...

After submitting the form, Axios sends multiple requests simultaneously

Recently, I embarked on a small project that involves using Laravel and Nuxt Js. The main objective of the project is to create a form for adding users to the database. Everything seems to be progressing smoothly, but there's a minor issue that I&apos ...

If the condition is false, the Bootstrap 4 carousel will not transition to another slide

With Bootstrap 4, each slide contains a form section and there is a next button. I want to ensure that the carousel does not move to the next slide unless a certain variable is true (for form validation purposes). I have attempted using the onclick event ...

The post function is causing an issue and displaying an error

I am currently working on a test application that is based on the tutorial found at https://docs.angularjs.org/tutorial/step_00. The app is functioning well, however, I am encountering an issue with the post method. index.html ... <div class="control_ ...

"Embedding PHP code within HTML tags, which is then embedded within

Running into an issue within a while loop... echo 'var contentString = '<div id="content" > <div id="bodyContent"> <p>' + $row[name]+ '</p> ...

Attempting to include a new choice on a drop-down menu and ensure its visibility within the drop-down menu

On my journey into the world of web development, I am facing a challenge with adding an option to a dropdown list. Despite pressing the add button to insert "Pasta" as a new option, it is not showing up in the list immediately. However, selecting all optio ...

Using ng-init to pass a JSON object

I'm attempting to pass a JSON Object to my application using ng-init and the stringify method, but I am encountering an error. Instead of working as expected, I am getting a Lexer error. Lexer Error: Unexpected next character at columns 8-8 [#] in ex ...

Trigger functions by clicking or bind click events by calling a function?

I need help comparing two similar code snippets: myFunc(); function myFunc() { var e = document.getElementByClassName("link"), i = e.length; while (i--) { e[i].addEventListener("click", function() { //do stuff for each ...

What can I do to prevent masonry images from piling on top of one another?

I have been working on creating a photo gallery using the Bootstrap 5 example on masonry, and everything is working well so far. I have also successfully implemented modal boxes. However, the only issue I'm facing is with the JS Image Loaded not preve ...

Unit testing promises in Angular using Jasmine

My goal is to create a unit test that demonstrates the process of combining two promises using $q.all in Angular, and then confirming that both promises are resolved simultaneously. describe("Application controller", function() { var scope; var ...

Resolving the Persistence Problem of Navigation Bar Fading In and Out

I've been struggling for hours trying different methods to achieve the desired outcome, but unfortunately, none of them have worked as expected. My goal is simple: I want the fixedbar to fade in when the scroll position exceeds the position of the ph ...

JavaScript Email Verification

I am designing my website and encountering an issue with the email checker. I can't figure out why it's not working, especially since I have never used JavaScript before. This is what I tried: var flag=true; var st = Form1["email"].value.ind ...