Как предотвратить скрытие изображения за пределами границ - PullRequest
0 голосов
/ 04 августа 2020

Итак, в настоящее время я создаю видеоигру, в которой мое изображение перемещается с помощью контроллеров клавиатуры. Проблема в том, что этот значок выходит за границы экрана. Кто-нибудь знает, как с этим бороться (только js или css)? Спасибо

Иконка перемещается с контроллерами:

let display = document.getElementById("body").style.width
let rect = document.getElementById("icon-p1")
let pos = {top: 85, left: 600}
const keys = {}
window.addEventListener("keydown", function(e) {keys[e.keyCode] = true})
window.addEventListener("keyup", function(e) {keys[e.keyCode] = false})
const loop = function() {
if (keys[37] || keys[81]) {pos.left -= 10; if (display < 100) {pos.left -= 0}}
if (keys[39] || keys[68]) {pos.left += 10; if (display < 100) {pos.left += 0}}
if (keys[38] || keys[90]) {pos.top -= 1; if (display < 100) {pos.top -= 0}}
if (keys[40] || keys[83]) {pos.top += 1; if (display < 100) {pos.top += 0}}
rect.style.left = pos.left + "px"; rect.style.top = pos.top + "%"}
let sens = setInterval(loop, 1000 / 40)

Css за фоновое изображение:

body {
background-image: url(Photo/bg.jpg);
background-repeat: no-repeat;
background-attachment: fixed;
background-size: cover;
overflow: hidden; }

1 Ответ

0 голосов
/ 04 августа 2020

Проверьте, достаточно ли удален ящик от границ:

// just storing the movement increment in a variable to make code softer
let moveInc = 10; 

// this is the width of the boundary. If the boundary/container has a width of 600px, this will be 600.
let containerWidth = document.getElementById("yourContainerID/screenID").style.width;

// this is the height of the boundary. If the boundary/container has a height of 800px, this will be 800.
let containerHeight = document.getElementById("yourContainerID/screenID").style.height;

// here is the function from your code
const loop = function() {

    // you will be better off formatting your code to match mine (aka no one-liner if statements)
    if (keys[37] || keys[81]) {
        if (pos.left > 0 + moveInc)// 0 is the left boundary, and the moveInc will act as a buffer to stop any overlap with the left boundary
            pos.left -= moveInc;
    }
    if (keys[39] || keys[68]) {
        if (pos.left + rect.style.width < containerWidth - moveInc)// containerWidth is the right boundary, again moveInc is a buffer
            pos.left += moveInc;
    }
    ...
}

Тогда вы можете использовать тот же принцип для верха и низа.

Верх будет сопоставим с левым

Внизу будет аналогично правому

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...