こんにちは私は基本的なポンゲームを作っています。プレーヤーオブジェクトをdrawPlate
に渡すと、情報を出力するように見えますが、Uncaught TypeError例外がスローされます。es6クラスオブジェクトが定義されていません
私のdraw()メソッドで情報をうまく印刷しているようです。ここで
は私のコードです:
"use strict";
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
var x = canvas.width/2;
var y = canvas.height - 20;
var offX = 5;
var offY = -5;
var radius = 8;
/**
* This is the constructor of a player object, parameters are the coordinates of x and y
*/
class Player {
constructor(x, y) {
this.x = x;
this.y = y;
this.moveRight = false;
this.moveLeft = false;
}
}
/**
* Here we add an event listener to see when the user presses a keyd, and make the plate move.
*/
document.addEventListener("keydown", handleKeyDown, false);
document.addEventListener("keyup", handleKeyUp, false);
function handleKeyDown(event) {
switch (event.key) {
case "ArrowRight":
player1.moveRight = true;
break;
case "ArrowLeft":
player1.moveLeft = true;
break;
default:
return;
}
}
function handleKeyUp(event) {
switch (event.key) {
case "ArrowRight":
player1.moveRight = false;
break;
case "ArrowLeft":
player1.moveLeft = false;
break;
default:
return;
}
}
function drawPlate(player1, player2) {
console.log(player1.x);
ctx.beginPath();
if (player1.moveRight == true) {
player1.x += 7;
} else if (player1.moveLeft == true) {
player1.x -= 7;
}
ctx.rect(player1.x, player1.y, canvas.width/7, 8);
ctx.fillStyle = "blue";
ctx.fill();
ctx.closePath();
ctx.beginPath();
ctx.rect(player2.x, player2.y, canvas.width/7, 8);
ctx.fillStyle = "green";
ctx.fill();
ctx.closePath();
}
function drawBall() {
ctx.beginPath();
ctx.arc(x, y, radius, 0, 2 * Math.PI);
ctx.fillStyle = "red";
ctx.fill();
ctx.closePath();
}
function draw(player1, player2) {
ctx.clearRect(0, 0, canvas.width, canvas.height);
drawBall();
drawPlate(player1, player2);
if (x + radius > canvas.width || x - radius < 0) {
offX = -offX;
}
if (y - radius < 0) {
offY = -offY;
} else if (y + radius > canvas.height) {
alert("GAME OVER");
location.reload();
}
x += offX;
y += offY;
requestAnimationFrame(draw);
}
var player1 = new Player(canvas.width/2 - 20, 0);
var player2 = new Player(canvas.width/2 - 2, canvas.height - 8);
//console.log(player2.x);
draw(player1, player2);
デルタ時間の引数。 – Dai