0

我试图弄清楚如何修复图像坐标,使其不会超出画布边框,但我找不到一个好的解决方案。

这就是我所拥有的:

function update(event) {

    if (event.keyCode == 38) { //going up
        if (py - speed < 0) {
            py = speed; return
        }
        py -= speed;
    }
    if (event.keyCode == 37) { //going left
        if (px < speed) {
            px = speed;
            return;
        }
        px -= speed;
    }
    if (event.keyCode == 40) { //going down
        if (py > ch-(ph+speed)) {
            py = ch-(ph-speed); return
        }
        py += speed;
    }

    if (event.keyCode == 39) { //going right
        if (px+pw > cw ) {
            px = (cw - pw); 
            return
        }
        px += speed;
    }
    $("#position").html(px + " " + py);
    render();
}

这是我的 js 小提琴:http: //jsfiddle.net/phjUL/2/

4

2 回答 2

1

在对它们应用所有更改,您可以简单地钳制pxpy到给定范围。例如。在你调用你的更新方法之前,像这样钳制你的值:render

// this will clamp px to a value between 0 and cw (canvas width)
px = Math.max(0, Math.min(px, cw));

// clamp py to a value between 0 and canvas height
py = Math.max(0, Math.min(py, ch));

您的更新方法将如下所示:

function update(event) {
    if (event.keyCode == 38) { //going up
        py -= speed;
    }
    if (event.keyCode == 37) { //going left
        px -= speed;
    }
    if (event.keyCode == 40) { //going down
        py += speed;
    }
    if (event.keyCode == 39) { //going right
        px += speed;
    }
    px = Math.max(0, Math.min(px, cw));
    py = Math.max(0, Math.min(py, ch));
    $("#position").html(px + " " + py);
    render();
}

链接到更新的小提琴:http: //jsfiddle.net/phjUL/4/

于 2013-07-27T12:20:33.637 回答
0

我认为最好的方法是先移动它,然后检查它是否超出范围并将其移回。http://jsfiddle.net/phjUL/3/

        function update(event) {

            if (event.keyCode == 38) { //going up
                py -= speed;
                if(py < 0) {
                    py = 0;
                }
            }
            if (event.keyCode == 37) { //going left
                px -= speed;
                if(px < 0) {
                    px = 0;
                }
            }
            if (event.keyCode == 40) { //going down
                py += speed;
                if(py > ch - ph) {
                    py = ch - ph;
                }
            }
            if (event.keyCode == 39) { //going right
                px += speed;
                if(px > cw - pw) {
                    px = cw - pw;
                }
            }

            $("#position").html(px + ", " + py);
            render();
        }
于 2013-07-27T11:58:09.867 回答