当前位置: 首页 > 知识库问答 >
问题:

球间碰撞检测

景阳平
2023-03-14

这两个球在画布上弹来弹去。

如果球碰撞了,帆布应该说游戏结束。

这是一个代码,我已经为碰撞到目前为止

function collideWithBall() {

              var dx = (ball.x + ball.radius) - (ballm.x + ballm.r);
              var dy = (ball.y + ball.radius) - (ballm.y + ballm.r);
              var distance = Math.sqrt((dx * dx) + (dy * dy));
              if (distance < ball.radius + ballm.r) {                 

                  ctx.clearRect(0, 0, canvas.width, canvas.height);    
                  ctx.fillStyle = "black";
                  ctx.font = "18px Arial";
                  ctx.fillText("Game Over ", 300, 200);
                  shutdown();

              }         
          }
<!DOCTYPE html>

<html>

  <head>
    <meta charset="UTF-8">
    <title>Canvas</title>

    <style type="text/css">
      canvas {
        border: 1px solid black;
      }
    </style>

  </head>

  <body>

      <canvas id="tim's-game" width="800px" height="600px"></canvas>

      <script type="text/javascript">
          // up top. creates the canvas with given dimensions
          // declares script type


          // Gets a handle to the element with id canvasOne.      
          var canvas = document.getElementById("tim's-game");      
          // Get a 2D context for the canvas.     
          var ctx = canvas.getContext("2d");      

          // Creates object for the balls 
          var ball = {
              // determines the position where the ball will apear math.random gives a random position on the x ace
              position: {x: Math.floor((Math.random() * 780) + 20), y: 10}
              // Will determine the size of the ball
              , radius: 6
              // Will determine the speed of the ball
              , velocity: {x: 3, y: 0}
              // Will determine if the ball will get faster or slower
              , acceleration: {x: 0, y: 0.1}        
              // Function that draws the ball  
              ,drawBall: function(){                  
                  // Collour of the object         
                  ctx.fillStyle = "rgb(25, 100, 100)";  
                  // begins path
                  ctx.beginPath();
                  // calls the object it will draw with positions and size
                  ctx.arc(ball.position.x, ball.position.y, ball.radius, 0, 2 * Math.PI);
                  // fills the colour 
                  ctx.fill();       



                  // Update the y location.
                  ball.velocity.y += ball.acceleration.y;
                  ball.position.x += ball.velocity.x;
                  ball.position.y += ball.velocity.y;
                  // Keep the animation going while the ball has not touched the canvas bottom.
                  // Note there's a bug here.
                  if ((ball.position.x >= canvas.width - ball.radius) ||  (ball.position.x <=                 ball.radius))
                      ball.velocity.x = -ball.velocity.x;    
                  if ((ball.position.y >= canvas.height - ball.radius) ||  (ball.position.y <=              ball.radius))
                      ball.velocity.y = -ball.velocity.y;   



              }
              ,

          }

          // Created a second ball object
          var ball2 = {
              // determines the position where the ball will apear math.random gives a random position on the x ace
              position: {x: Math.floor((Math.random() * 780) + 20), y: 10}
              // Will determine the size of the ball
              , radius: 6
              // Will determine the speed of the ball
              , velocity: {x: 3, y: 0}
              // Will determine if the ball will get faster or slower
              , acceleration: {x: 0, y: 0.1}        
              // Function that draws the ball  
              ,drawBall2: function(){                  
                  // Collour of the object         
                  ctx.fillStyle = "rgb(25, 100, 100)";  
                  // begins path
                  ctx.beginPath();
                  // calls the object it will draw with positions and size
                  ctx.arc(ball2.position.x, ball2.position.y, ball2.radius, 0, 2 * Math.PI);
                  // fills the colour 
                  ctx.fill();       


                  // Update the y location.
                  ball2.velocity.y += ball2.acceleration.y;
                  ball2.position.x += ball2.velocity.x;
                  ball2.position.y += ball2.velocity.y;
                  // Keep the animation going while the ball has not touched the canvas bottom.
                  // Note there's a bug here.
                  if ((ball2.position.x >= canvas.width - ball2.radius) ||  (ball2.position.x <= ball2.radius))
                      ball2.velocity.x = -ball2.velocity.x;    
                  if ((ball2.position.y >= canvas.height - ball2.radius) ||  (ball2.position.y <= ball2.radius))
                      ball2.velocity.y = -ball2.velocity.y;
              }
          }


          // Creates a new ball object 
          // This ball will be used for moving around the canvas
          var ballm = {
              // spawns the ball in the middle of the canvas
              position:{ x: canvas.width / 2
              , y: canvas.height / 2
              }, r: 50

          };

          // Creates a draw circle function
          function drawCircle() {
              ctx.fillStyle = "rgb(255, 0, 0)";
              ctx.beginPath();
              ctx.arc(ballm.position.x, ballm.position.y, ballm.r, 0, 2 * Math.PI);
              ctx.fill();

              collideWithBall();

          }

          function collideWithBall() {


              var dx = (ball.position.x + ball.radius) - (ballm.position.x + ballm.r);
              var dy = (ball.position.y + ball.radius) - (ballm.position.y + ballm.r);
              var distance = Math.sqrt((dx * dx) + (dy * dy));
              if (distance < ball.radius + ballm.r) {                 

                  ctx.clearRect(0, 0, canvas.width, canvas.height);    
                  ctx.fillStyle = "black";
                  ctx.font = "18px Arial";
                  ctx.fillText("Game Over ", 300, 200);
                  shutdown();

              }         
          }



          // A function to repeat every time the animation loops.
          function repeatme() {

              collideWithBall();
              // clears  the screan/canvas i.e. where the ball was previously does not show up.
              ctx.clearRect(0, 0, canvas.width, canvas.height);
              // calls the function in the ball object
              ball.drawBall();
              ball2.drawBall2();

              //calls the draw circle function
              drawCircle();

              collideWithBall();
              // gets the animation going
              window.requestAnimationFrame(repeatme);  
          }

          // Add an event listener to the keypress event.          
          window.addEventListener("keydown", function(event) {

              ctx.clearRect(0, 0, canvas.width, canvas.height);

              // Right
              if (event.keyCode == 39 && ballm.position.x < canvas.width - ballm.r)
                  ballm.position.x += Math.min(10, canvas.width - ballm.position.x - ballm.r);

              // Left
              else if (event.keyCode == 37 && ballm.position.x > ballm.r)
                  ballm.position.x -= 10;

              // down
              else if (event.keyCode == 40 && ballm.position.y < canvas.height - ballm.r)
                  ballm.position.y += 10;

              // For up movement
              else if (event.keyCode == 38 && ballm.position.y > ballm.r)
                  // updates location by int given
                  ballm.position.y -= 10;

              drawCircle();
                collideWithBall();
          });


          // Get the animation going.

          window.requestAnimationFrame(repeatme);
    </script>

  </body>

</html>

共有1个答案

凤高翰
2023-03-14

我认为你的数学是错的。您的支票

if (distance < ball.radius + ballm.r) { 

是正确的,但意味着距离是以球的中心到中心来测量的。因此正确的距离公式为:

var dx = ball.position.x-ballm.x;
var dy = ball.position.y-ballm.y;
var distance = Math.sqrt((dx * dx) + (dy * dy));

如果您测量的是if语句所暗示的中心到中心的距离,则球的半径不会进入计算。

collideWithBall
 类似资料:
  • 我遵循Mozilla游戏开发教程,并在HTML5 Canvas和JS中制作了一个简单的突破游戏。 然而,我想放大画布,因为它有点小,所以我尝试了800x600画布。然后,我注意到对于这个新的画布大小来说,球有点慢。 最初在mozilla教程中,球的速度是2。我尝试使用3。因此,问题就来了。。。 当我使用每秒刷新60倍的requestAnimationFrame时,我们可以说我的球将每秒移动3 x

  • 碰撞检测 现在你知道了如何制造种类繁多的图形对象,但是你能用他们做什么?一个有趣的事情是利用它制作一个简单的 碰撞检测系统 。你可以用一个叫做:hitTestRectangle 的自定义的函数来检测两个矩形精灵是否接触。 hitTestRectangle(spriteOne, spriteTwo) 如果它们重叠, hitTestRectangle 会返回 true。你可以用 hitTestRect

  • 本节暂未进行完全的重写,错误可能会很多。如果可能的话,请对照原文进行阅读。如果有报告本节的错误,将会延迟至重写之后进行处理。 当试图判断两个物体之间是否有碰撞发生时,我们通常不使用物体本身的数据,因为这些物体常常会很复杂,这将导致碰撞检测变得很复杂。正因这一点,使用重叠在物体上的更简单的外形(通常有较简单明确的数学定义)来进行碰撞检测成为常用的方法。我们基于这些简单的外形来检测碰撞,这样代码会变得

  • 基本上我在做一个游戏的过程中,这是像乒乓球,突破等,我有一些问题时,球和桨碰撞。。。但只是有时候! 下面的视频是正在发生的事情:http://www.youtube.com/watch?v=uFZIxFIg0rI 所以是的,基本上,当球与球拍相撞时,它有时会变得有点疯狂......通常情况下,如果我将球拍移动到球接近它的相反方向。此外,球有时会被夹在游戏窗口的底部和球拍之间......即使我有代码

  • The Sphere Collider is a basic sphere-shaped collision primitive. 球体碰撞器是一个基本的球体形状的原型碰撞器。 A pile of Sphere Colliders 一堆球体碰撞器 Properties 属性 Material 材质 Reference to the Physic Material that determines h

  • 问题内容: 有人可以帮我了解JS中冲突检测的工作原理吗?我不能使用jQuery或gameQuery-已经使用了原型- 因此,我正在寻找非常简单的东西。不要求完整的解决方案,只需为我指明正确的方向。 假设有: 现在球正在移动(任何方向)。“ Someobject”(0-X)已经预先定义,其中有20-60个随机放置,如下所示: 我可以创建一个位置为“ someobject(X)”的数组,并在“球”移动