屏幕跟随“角色”

时间:2018-05-20 16:55:07

标签: javascript jquery html animation

我正在努力实现以下图片, enter image description here

然后,只要玩家移动(他通过点击移动),我希望可见区域与他一起移动。可见区域应显示在整个屏幕上。

我目前有以下代码但我不知道如何制作它只是可见区域可见;

代码

<body>
            <div class="map">       
                <div class="screen">
                    <div class="player">
                        <img class="ship" src="https://vignette.wikia.nocookie.net/darkorbit/images/a/a9/Neuergoli.jpg/revision/latest?cb=20120819231510">
                    </div>
                </div>
            </div>
        </body>

$(function(){
    $('.map .screen').on('click', function(event){
        var clickedPosX = event.pageX,
                clickedPosY = event.pageY;

        var $player = $('.screen');
        $player.animate({left:clickedPosX, top:clickedPosY}, 1000);
    });
});

JSFiddle

1 个答案:

答案 0 :(得分:0)

尝试这个

$(function(){
    var $map = $(".map");
    var $player = $('.player');

    var centerPlayerX = $player.offset().left + $player.width() / 2;
    var centerPlayerY = $player.offset().top + $player.height() / 2;

    $('.map').on('click', function(event){
        var clickedPosX = event.pageX,
            clickedPosY = event.pageY;

        var currentMapPositionX = parseFloat($map.css("background-position-x"));
        var currentMapPositionY = parseFloat($map.css("background-position-y"));

        var moveMapX = currentMapPositionX - clickedPosX + centerPlayerX;
        var moveMapY = currentMapPositionY - clickedPosY + centerPlayerY;

        $map.animate({ "background-position-x": `${moveMapX}px`, "background-position-y":  `${moveMapY}px` }, 1000);
    });
});

并将background-repeat: repeat;添加到.map css