gpt4 book ai didi

javascript - 球与矩形碰撞检测 Canvas javascript

转载 作者:行者123 更新时间:2023-12-01 02:27:55 25 4
gpt4 key购买 nike

最近我开始学习 Canvas 动画,并一直在网上学习一些教程等。然而,在数学方面我已经开始触及一些界限。一个特殊的问题涉及一旦球击中 Canvas 内的 div 元素,就会反转球的 x 和 y 坐标。下面可以看到球的预期所需运动的图片表示。

cavas image

如您所见,我希望球的 x 和 y 坐标根据所触摸的 div 的一侧而变化。

目前,球确实在 Canvas 两侧正确弹起,并且也从主 div 的左侧和右侧正确弹起。然而,一旦球击中主分区的顶部或底部,逻辑就会崩溃。我的项目代码如下所示。

var canvas = document.querySelector('canvas');
var content = document.querySelector('.main-content h1');

var contentPosition = content.getBoundingClientRect();

canvas.width = window.innerWidth;
canvas.height = window.innerHeight;

var radius = 10;
var maxRadius = 20;

var mouse = {
x: undefined,
y: undefined
}

var colour = [
'#FF530D',
'#E82C0C',
'#FF0000',
'#E80C7A',
'#FF0DFF'
];

window.addEventListener('mousemove', function(event){

mouse.x = event.x;
mouse.y = event.y;

});

//c = context
var c = canvas.getContext('2d');

function circle(x, y, dx, dy, radius){

this.x = x;
this.y = y;
this.dx = dx;
this.dy = dy;
this.radius = radius;
this.minRadius = Math.floor(Math.random() * 10 + 1);
this.fillColour = colour[Math.floor(Math.random() * colour.length )];

this.draw = function(){

c.beginPath();
c.arc(this.x, this.y, this.radius, 0, Math.PI*2);
c.fillStyle = this.fillColour;
c.fill();
c.closePath();
}

this.update = function(){

if(this.x + this.radius > innerWidth || this.x - this.radius < 0){

this.dx =- this.dx;
}

if(this.y + this.radius >= innerHeight || this.y - this.radius < 0){

this.dy =- this.dy;
}

if(this.x + this.radius > contentPosition.left && this.x - this.radius < contentPosition.right && this.y + this.radius > contentPosition.top && this.y - this.radius < contentPosition.bottom){
this.dx =- this.dx;
}

if(this.x - mouse.x < 50 && (this.x - mouse.x) > -50
&& this.y - mouse.y < 50 && this.y - mouse.y > -50){

if(this.radius < maxRadius){
this.radius +=2;
}
}
else if(this.radius > this.minRadius){
this.radius -= 2;
}

this.x += this.dx;
this.y += this.dy;

this.draw();

}


}

circleArray = [];

function getDistance(x1, y1, x2, y2){

var xDistance = x2 - x1;
var yDistance = y2 - y1;

return Math.sqrt( Math.pow(xDistance, 2) + Math.pow(yDistance, 2));
}

function randomIntFromInterval(min,max)
{
return Math.floor(Math.random()*(max-min+1)+min);
}

function init(){

for(i = 0; i < 100; i++){

x = randomIntFromInterval(radius, innerWidth - radius);
y = randomIntFromInterval(radius, innerHeight - radius);

dx = (Math.random() - 0.5) * 2;
dy = (Math.random() - 0.5) * 2;


circleArray.push(new circle(x, y, dx, dy, radius));
}

}

function animate(){

requestAnimationFrame(animate);
c.clearRect(0, 0, innerWidth, innerHeight);

for(i = 0; i < circleArray.length; i++){
circleArray[i].update();
}

}

init();
animate();
canvas {
position: fixed;
z-index: -9999;
}

body {
margin: 0;
}

.main-content{
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}

.main-content h1{
font-weight: 700;
font-size: 40px;
text-shadow: 0 0 2px #464646;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<script src="http://code.jquery.com/jquery-3.3.1.slim.js" integrity="sha256-fNXJFIlca05BIO2Y5zh1xrShK3ME+/lYZ0j+ChxX2DA=" crossorigin="anonymous"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<link rel="stylesheet" href="styles.css">
<title>Canvas Test</title>
</head>
<body>
<canvas></canvas>

<div class="main-content">
<h1 class="text-center">Example Text For Main Div</h1>
</div>

<script src="canvas.js"></script>
</body>
</html>

上面演示了整个工作逻辑。上面代码片段中检测与主 div 碰撞的代码如下。

 if(this.x + this.radius > contentPosition.left && this.x - this.radius < contentPosition.right  && this.y + this.radius > contentPosition.top && this.y - this.radius < contentPosition.bottom){
this.dx =- this.dx;
}

目前,一旦 div 的左侧或右侧被球击中,只有球的 x 坐标会发生变化。如果主 div 的顶部或底部被击中,我需要进行此调整以包括 Y 坐标的更改。

任何有关如何更正我的代码的建议或任何基于在线数学 Material 的知识(将指向答案)将不胜感激。

提前致谢

更新

根据答案中给出的代码更新圆投影路径

enter image description here

最佳答案

更新以通知网格问题已得到解决,并包含显示正在运行的解决方案的代码片段。

根据给定的图像,我假设圆圈始终从矩形外部开始,并且矩形始终与轴对齐。您可以根据相应的一对墙将 x 和 y 否定分开。下面的解决方案测试圆位于 div 一侧中间的时刻。

// Aliases to avoid thinking of offsetting positions
var circleTop = this.y - this.radius;
var circleBottom = this.y + this.radius;
var circleLeft = this.x - this.radius;
var circleRight = this.x + this.radius;

// For uniformity with circle
var rectTop = contentPosition.top;
var rectBottom = contentPosition.bottom;
var rectLeft = contentPosition.left;
var rectRight = contentPosition.right;

// Circle penetration on the div's left and right walls
if (((circleRight > rectLeft && circleLeft < rectLeft) ||
(circleLeft < rectRight && circleRight > rectRight)) &&
circleTop < rectBottom && circleBottom > rectTop) {

this.dx = -this.dx;
}

// Circle penetration on the div's top and bottom walls
if (((circleBottom > rectTop && circleTop < rectTop) ||
(circleTop < rectBottom && circleBottom > rectBottom)) &&
circleLeft < rectRight && circleRight > rectLeft) {

this.dy = -this.dy;
}

以下是你的代码,移植了我的代码。

var canvas = document.querySelector('canvas');
var content = document.querySelector('.main-content h1');

var contentPosition = content.getBoundingClientRect();

// For uniformity with circle
var rectTop = contentPosition.top;
var rectBottom = contentPosition.bottom;
var rectLeft = contentPosition.left;
var rectRight = contentPosition.right;

canvas.width = window.innerWidth;
canvas.height = window.innerHeight;

var radius = 10;
var maxRadius = 20;

var mouse = {
x: undefined,
y: undefined
}

var colour = [
'#FF530D',
'#E82C0C',
'#FF0000',
'#E80C7A',
'#FF0DFF'
];

window.addEventListener('mousemove', function(event){

mouse.x = event.x;
mouse.y = event.y;

});

//c = context
var c = canvas.getContext('2d');

function circle(x, y, dx, dy, radius){

this.x = x;
this.y = y;
this.dx = dx;
this.dy = dy;
this.radius = radius;
this.minRadius = Math.floor(Math.random() * 10 + 1);
this.fillColour = colour[Math.floor(Math.random() * colour.length )];

this.draw = function(){

c.beginPath();
c.arc(this.x, this.y, this.radius, 0, Math.PI*2);
c.fillStyle = this.fillColour;
c.fill();
c.closePath();
}

this.update = function(){

if(this.x + this.radius > innerWidth || this.x - this.radius < 0){

this.dx =- this.dx;
}

if(this.y + this.radius >= innerHeight || this.y - this.radius < 0){

this.dy =- this.dy;
}

// Aliases to avoid thinking of offsetting positions
var circleTop = this.y - this.radius;
var circleBottom = this.y + this.radius;
var circleLeft = this.x - this.radius;
var circleRight = this.x + this.radius;

// Circle penetration on the div's left and right walls
if (((circleRight > rectLeft && circleLeft < rectLeft) ||
(circleLeft < rectRight && circleRight > rectRight)) &&
circleTop < rectBottom && circleBottom > rectTop) {

this.dx = -this.dx;
}

// Circle penetration on the div's top and bottom walls
if (((circleBottom > rectTop && circleTop < rectTop) ||
(circleTop < rectBottom && circleBottom > rectBottom)) &&
circleLeft < rectRight && circleRight > rectLeft) {

this.dy = -this.dy;
}

if(this.x - mouse.x < 50 && (this.x - mouse.x) > -50
&& this.y - mouse.y < 50 && this.y - mouse.y > -50){

if(this.radius < maxRadius){
this.radius +=2;
}
}
else if(this.radius > this.minRadius){
this.radius -= 2;
}

this.x += this.dx;
this.y += this.dy;

this.draw();

}


}

circleArray = [];

function getDistance(x1, y1, x2, y2){

var xDistance = x2 - x1;
var yDistance = y2 - y1;

return Math.sqrt( Math.pow(xDistance, 2) + Math.pow(yDistance, 2));
}

function randomIntFromInterval(min,max)
{
return Math.floor(Math.random()*(max-min+1)+min);
}

function init(){

for(i = 0; i < 100; i++){

x = randomIntFromInterval(radius, innerWidth - radius);
y = randomIntFromInterval(radius, innerHeight - radius);

dx = (Math.random() - 0.5) * 2;
dy = (Math.random() - 0.5) * 2;


circleArray.push(new circle(x, y, dx, dy, radius));
}

}

function animate(){

requestAnimationFrame(animate);
c.clearRect(0, 0, innerWidth, innerHeight);

for(i = 0; i < circleArray.length; i++){
circleArray[i].update();
}

}

init();
animate();
canvas {
position: fixed;
z-index: -9999;
}

body {
margin: 0;
}

.main-content{
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}

.main-content h1{
font-weight: 700;
font-size: 40px;
text-shadow: 0 0 2px #464646;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<script src="http://code.jquery.com/jquery-3.3.1.slim.js" integrity="sha256-fNXJFIlca05BIO2Y5zh1xrShK3ME+/lYZ0j+ChxX2DA=" crossorigin="anonymous"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<link rel="stylesheet" href="styles.css">
<title>Canvas Test</title>
</head>
<body>
<canvas></canvas>

<div class="main-content">
<h1 class="text-center">Example Text For Main Div</h1>
</div>

<script src="canvas.js"></script>
</body>
</html>

需要注意的是,如果你的圆的速度(你的 this.dxthis.dy)足够大,并且你的 div 和圆足够小,那么圆可以穿过 div 的墙壁而不触发上面的碰撞条件。在视频游戏碰撞编程中,这个问题称为隧道,并且涉及更多减轻影响的算法,例如提前投影运动中的形状并针对其阴影进行测试。

对于更复杂的情况,您可能会发现一些更复杂的碰撞算法很有帮助,例如 Separating Axis Theorem (SAT 算法)当您的形状不再轴对齐时。

关于javascript - 球与矩形碰撞检测 Canvas javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48596327/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com