gpt4 book ai didi

javascript - JavaScript 中的 Agario - 玩家不动

转载 作者:行者123 更新时间:2023-11-30 00:22:51 24 4
gpt4 key购买 nike

我的代码有问题,

// JavaScript Document
var canvas = document.getElementById("PlayingArea");
var ctx = canvas.getContext("2d");

var canvasWidth = canvas.width;
var canvasHeight = canvas.height;
var foodArray = [];
var size = 10;
var food;


var player1 = {x:150, y:150};

//create Player1
ctx.beginPath();
ctx.arc(150, 150, size, 0, Math.PI * 2);
ctx.fillStyle = "black";
ctx.fill();

function update() {
"use strict";

//BG Refresh
ctx.fillStyle = "white";
ctx.fillRect(0,0,canvasWidth,canvasHeight);
ctx.strokeStyle = "black";
ctx.strokeRect(0,0,canvasWidth,canvasHeight);


document.addEventListener("keydown", Player1Control);
function Player1Control(){
if(event.keyCode === 38) {
player1.y--;
}
if(event.keyCode === 40) {
player1.y++;
}
if(event.keyCode === 39) {
player1.x++;
}
if(event.keyCode === 37) {
player1.x--;
}
}

if (player1.x >= canvasWidth) {
player1.x = canvasWidth;
} else if (player1.x <= 5) {
player1.x = 5;
}

if (player1.y > canvasHeight) {
player1.y = canvasHeight;
} else if (player1.y <= 5) {
player1.y = 5;
}

//Player Show
ctx.beginPath();
ctx.arc(player1.x, player1.y, size, 0, Math.PI * 2);
ctx.fillStyle = "black";
ctx.fill();

//Food Show
for(var i=foodArray.length; i>0; i--){
ctx.beginPath();
ctx.arc({x:foodArray[i].x},{y:foodArray[i].y} , size, 0, Math.PI * 2);
ctx.fill();
}


setTimeout(update, 10);
}

function foodGen(){
"use strict";
food = {x:Math.round(Math.random()*(canvasWidth)),
y:Math.round(Math.random()*(canvasHeight))};
ctx.beginPath();
ctx.arc(food.x, food.y, 5, 0, Math.PI * 2);
ctx.fillStyle = "black";
ctx.fill();
foodArray.push({x:1,y:1});
setTimeout(foodGen, 1000);
}


update();
foodGen(0,750);

播放器没有显示在我的代码中,我不知道为什么我的播放器没有移动。我对 JavaScript 和 HTML/CSS 还很陌生。这是我第一次 Stack overflow,所以对于任何问题我深表歉意。

-lt1489

编辑:我的播放器现在出现在屏幕上,无法移动。链接:https://jsfiddle.net/5os0qrhp/2/

最佳答案

原始问题的回答如下:

Since you don't change fillStyle between clearing the canvas and drawing the player, you are drawing the player white. Since it is white on white, you cannot see the player.

关于第二个问题,将document.addEventListenerPlayer1Control移到update之外。此外,Player1Control 需要 event 作为参数,导致:

document.addEventListener("keydown", Player1Control);
function Player1Control(event) { ... }
function update() { ... }

一些语法更改修复了代码。参见 jsfiddle查看概述的这些更改。

关于javascript - JavaScript 中的 Agario - 玩家不动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32545657/

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