首页 > 解决方案 > 球从中心而不是边缘反弹

问题描述

我编写了一个球在画布上弹跳,但是,球只从中心弹跳,而不是从边缘弹跳。

我已经尝试使用半径而不是 x 和 y 但这根本没有帮助,因为现在我没有想法。

我希望球会从自身的边缘而不是中心反弹

<!DOCTYPE>
<html>

<head>
<title>Ball Bounce</title>

<style>


canvas {
border-width: 5px;
border-style: ridge;
border-color: #FF0000;
}

</style>

</head>


<body>

<canvas id="testCanvas" width="700" height="400"></canvas>

<script>

var canvas = document.getElementById("testCanvas");
var ctx = canvas.getContext("2d");


var x = 300;
var y = 300;
var radius = 50;
var circleColour = "green";

var canvasWidth = canvas.width; 
var canvasHeight = canvas.height;
var dx = 2;
var dy = -2;




function circle(x, y, r, c) {
ctx.beginPath();
ctx.arc(x, y, r, 0, 2 * Math.PI, false);
ctx.fillStyle = c;
ctx.fill()
ctx.closePath();
}

function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
circle(x, y, radius, circleColour)
if (y<0 || y > canvasHeight){
dy = -dy;
}

if (x>canvasWidth || x<0){
dx = -dx;
}



 x = x + dx;
 y = y + dy;
}

setInterval(draw, 5.5);

</script>



</body>

</html>

标签: javascriptcanvas

解决方案


我已经尝试过使用半径而不是 x 和 y 但这根本没有帮助......

您需要将半径与 x 和 y(或画布边缘)结合起来,以确保球在所有四个边界处改变方向。

if (y - radius < 0 || y + radius > canvasHeight) {
    dy = -dy;
}

if (x + radius > canvasWidth || x - radius < 0) {
    dx = -dx;
}

推荐阅读