gpt4 book ai didi

javascript - 如何通过碰撞检测更改 Canvas fillStyle?

转载 作者:行者123 更新时间:2023-12-02 14:59:25 26 4
gpt4 key购买 nike

所以我按照 this tutorial 制作了一个打砖 block 游戏这相当简单,但可选练习之一是让球在碰到 Canvas 一侧时改变颜色。该网站没有告诉您如何执行此操作,并且经过几个小时的谷歌搜索后我还没有找到任何答案。

我刚刚开始学习 Javascript,这是我为大学制作的一个简单游戏的练习,这个想法是如何改变颜色的知识将或多或少地转移到与墙壁碰撞时改变 Sprite 上.

为了简单起见,下面是让球移动并从墙壁上弹起的代码:

var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
var ballRadius = 10;
var x = canvas.width/2;
var y = canvas.height-30;
var dx = 2;
var dy = -2;


function drawBall() {
ctx.beginPath();
ctx.arc(x, y, ballRadius, 0, Math.PI*2);
ctx.fillStyle = "#0095DD";
ctx.fill();
ctx.closePath();
}

function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
drawBall();

if(x + dx > canvas.width-ballRadius || x + dx < ballRadius) {
dx = -dx;

}
if(y + dy > canvas.height-ballRadius || y + dy < ballRadius) {
dy = -dy;

}

x += dx;
y += dy;
}

setInterval(draw, 10);
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Gamedev Canvas Workshop</title>
<style>
* {padding: 0; margin: 0;}
canvas { background: #eee; display: block; margin: 0 auto;}
</style>
</head>
<body>

<canvas id="myCanvas" width="480" height="320"></canvas>

<script>

</script>


</body>
</html>

练习指定让球在每次碰撞时改变为新的随机颜色,但出于我的目的,我只需要知道如何让它改变一次。

最佳答案

这是一个简单的方法。

var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
var ballRadius = 10;
var x = canvas.width / 2;
var y = canvas.height - 30;
var dx = 2;
var dy = -2;
var color = "#0095DD"


function drawBall() {
ctx.beginPath();
ctx.arc(x, y, ballRadius, 0, Math.PI * 2);
ctx.fillStyle = color;
ctx.fill();
ctx.closePath();
}

function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
drawBall();

if (x + dx > canvas.width - ballRadius || x + dx < ballRadius) {
dx = -dx;
color = "#" + ((1 << 24) * Math.random() | 0).toString(16);
}
if (y + dy > canvas.height - ballRadius || y + dy < ballRadius) {
dy = -dy;
color = "#" + ((1 << 24) * Math.random() | 0).toString(16);
}

x += dx;
y += dy;
}

setInterval(draw, 10);
<!DOCTYPE html>
<html>

<head>
<meta charset="utf-8" />
<title>Gamedev Canvas Workshop</title>
<style>
* {
padding: 0;
margin: 0;
}
canvas {
background: #eee;
display: block;
margin: 0 auto;
}
</style>
</head>

<body>

<canvas id="myCanvas" width="480" height="320"></canvas>

<script>
</script>


</body>

</html>

关于javascript - 如何通过碰撞检测更改 Canvas fillStyle?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35544248/

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