这是我的代码:
var canvas = document.getElementById("canvas")
var ctx = canvas.getContext("2d")
var w = canvas.width
var h = canvas.height
var player = {
x: w / 2,
y: h / 2,
r: 10,
vx: 0,
vy: 0,
speed: 5,
}
var keys = []
window.onkeydown = function(event) {keys[event.keyCode] = true}
window.onkeyup = function(event) {keys[event.keyCode] = false}
setInterval(update, 1000 / 60)
function update() {
if (keys[38] && player.vy > -player.speed) {
player.vy--
}
if (keys[40] && player.vy < player.speed) {
player.vy++
}
if (keys[37] && player.vx > -player.speed) {
player.vx--
}
if (keys[39] && player.vx < player.speed) {
player.vx++
}
player.vx *= 0.9
player.vy *= 0.9
player.x += player.vx
player.y += player.vy
ctx.clearRect(0,0,w,h)
ctx.beginPath()
ctx.arc(player.x, player.y, player.r, 0, Math.PI * 2, false)
ctx.fillStyle = "red"
ctx.fill()
}
所以,我的问题是,当你走出界限时,如何让玩家出现在另一边?现在这很容易完成,所以还有一件事,当一半球员超出界限时,我希望双方看到一半,就像这样:
答案 0 :(得分:1)
你可以这样做:
// coordinates replaced in the board
player.x = (player.x+w)%w;
player.y = (player.y+h)%h;
// player position drawing
ctx.clearRect(0,0,w,h)
ctx.beginPath()
for (var i=-1; i<=1; i++) {
for (var j=-1; j<=1; j++) {
var x = player.x+i*w, y = player.y+j*h;
if (x+player.r<0 || x-player.r>w || y+player.r<0 || y-player.r>h) continue;
ctx.arc(x, y, player.r, 0, Math.PI * 2, false)
}
}