gpt4 book ai didi

Javascript使圆圈正确命中 Canvas 边框

转载 作者:行者123 更新时间:2023-11-28 16:37:40 27 4
gpt4 key购买 nike

我目前正在开发一个小游戏,但我无法让圆圈正确击中左侧和顶部 Canvas 边框。它正确地击中了右侧和底部。

圆可以用 W A S D 移动,并且必须正确地碰到 Canvas 的所有边界

这是代码:http://jsfiddle.net/tumy8kbh/

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>JS Game</title>
<link rel="stylesheet" href="css/style.css" type="text/css" />
<script type="text/javascript" src="js/jquery-2.1.4.min.js"></script>
</head>
<body>

<canvas id="myCanvas" width="1200" height="800"></canvas>

<script>
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
var dx = 2;
var dy = -2;
var playerRadius = 80;
var playerX = (canvas.width-playerRadius)/2;
var playerY = (canvas.height-playerRadius);
var rightPressed = false;
var leftPressed = false;
var upPressed = false;
var downPressed = false;

document.addEventListener("keydown", keyDownHandler, false);
document.addEventListener("keyup", keyUpHandler, false);

function keyDownHandler(e) {
if(e.keyCode == 87) {
upPressed = true;
}
else if(e.keyCode == 83) {
downPressed = true;
}
else if(e.keyCode == 68) {
rightPressed = true;
}
else if(e.keyCode == 65) {
leftPressed = true;
}
}
function keyUpHandler(e) {
if(e.keyCode == 87) {
upPressed = false;
}
else if(e.keyCode == 83) {
downPressed = false;
}
else if(e.keyCode == 68) {
rightPressed = false;
}
else if(e.keyCode == 65) {
leftPressed = false;
}
}

function drawPlayer(){
ctx.beginPath();
ctx.arc(playerX, playerY, playerRadius, 0, Math.PI*2);
ctx.fillStyle = "#0095DD";
ctx.fill();
ctx.closePath();
}

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

if(rightPressed && playerX < canvas.width-playerRadius) {
playerX += 7;
}
else if(leftPressed && (playerX - playerRadius) > 0) {
playerX -= 7;
}
else if(upPressed && (playerY - playerRadius) > 0) {
playerY -= 7;
}
else if(downPressed && playerY < canvas.height-playerRadius) {
playerY += 7;
}

if(playerX >= canvas.width){
leftPressed = false;
}
}

setInterval(draw, 10);

</script>


</body>
</html>

如果您需要更多信息,请说明。

最佳答案

这与您检查球是否可以移动的方式有关。您检查 X - 半径是否 > 0,然后向左移动 7。如果球距离左边缘 1 个像素,它可以移动,但最终会向左移动 6 个像素。计算新的 X 位置后,再次检查 X - 半径是否不小于 0 ...相应地调整 X ...您需要对所有方向执行相同的操作(如果固定顶部,底部和右侧将停止工作然后向左移动到顶部/左侧,然后移动到右下角 – Jaromanda X

关于Javascript使圆圈正确命中 Canvas 边框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34239598/

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