سؤال

Here's my code:

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()
}

http://jsfiddle.net/wfNse/

So, my question is, how can I make the player come out on the other side when you go out side of the bounds? Now this is pretty easily done, so there's one more thing, when half the player is out of the bounds, I want it to be seen half on both sides, like this:

(Made with paint)

هل كانت مفيدة؟

المحلول

You can do this :

// 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)    
    }
}    

Demonstration

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top