我一直在研究JS,并决定制作一个乒乓球'一个球弹跳两个平行桨的游戏,一个由箭头键控制,另一个由AI控制。我正在使用Brackets编译我的代码。我的问题是我想导入我所做的外部函数,所以我的代码看起来很整洁,但没有任何显示。这是我的主要游戏代码和我的外部函数代码:
<html>
<canvas id="gameCanvas" width="800" height="600"></canvas>
<script>
import {drawRect} from 'useful functions';
var canvas;
var canvasContext;
var ballX = 0;
var ballY = 300 - ballSize/2;
var ballSize = 10;
var ballSpeedX = 5;
window.onload = function()
{
canvas = document.getElementById('gameCanvas');
canvasContext = canvas.getContext('2d');
var FPS = 60;
setInterval(function() {
moveEverything();
drawEverything();
}, 1000/FPS);
}
function moveEverything()
{
ballX = ballX + ballSpeedX;
if (ballX > (canvas.width - ballSize)) {
ballSpeedX = -ballSpeedX;
}
}
function drawEverything()
{
drawRect(ballY, ballX, ballSize, ballSize, 'red');
}
</script>
</html>
我的外部功能代码:
<script>
export function drawRect(x, y, width, height, colour) {
canvasContext.fillStyle(colour);
canvasContext.fillRect(x, y, width, height);
}
</script>
顺便说一句,我的主要代码是.html,我的扩展名是.js
感谢您阅读和快乐编码!