gpt4 book ai didi

javascript - es6 类对象未定义

转载 作者:行者123 更新时间:2023-12-03 06:28:13 25 4
gpt4 key购买 nike

嗨,我正在制作一个基本的乒乓球游戏,当我将玩家对象传递到 drawPlate 时,它看起来会打印信息,但随后会抛出 Uncaught TypeError 异常。

在我的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);

最佳答案

问题是,您首先通过传入player1和player2来调用draw,但随后使用requestAnimationFrame(draw)再次调用它,这不会传递这些变量沿(而不是 requestAnimationFrame 调用带有时间戳的绘制方法)。

在这种情况下,由于您无论如何都使用全局变量,因此我只需从绘制函数中删除 person1person2 参数,并处理player1/player2变量作为全局变量。

所以你所要做的就是将绘制函数更改为:

function draw() {
// Rest of the code
}

稍后调用它,而不传递任何内容:

var player1 = new Player(canvas.width / 2 - 20, 0);
var player2 = new Player(canvas.width / 2 - 2, canvas.height - 8);
draw();

关于javascript - es6 类对象未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38547326/

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