L
L
lord_Iohan2019-07-10 18:27:25
JavaScript
lord_Iohan, 2019-07-10 18:27:25

How to make the animation of the character jump on the block correctly?

I have a character that can jump onto a block and get off it, but he can't jump on the block itself. I can't figure out how to fix it so I can. The function where I'm trying to do all this is called moveMan.

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Jump</title>
</head>
<body>
<div style="position: relative;">
<canvas id="fon" style="position: absolute" width="928" height="600"></canvas>
<canvas id="field" width="928" height="600" style="position: absolute">hi</canvas>
</div>
<script>
    const canvasFon = document.getElementById('fon');
    let ctxFon = canvasFon.getContext('2d');
    const canvas = document.getElementById('field');
    let ctx = canvas.getContext('2d');

    ctxFon.fillStyle = 'black';
    let secondLineX = 250,
        thirdLineY = 450,
        secondWidth = 428;
    ctxFon.fillRect(secondLineX, thirdLineY, secondWidth, 25);

    function jack() {
        let sprite = new Image();
        sprite.src = 'https://www.emu-land.net/forum/index.php?action=dlattach;topic=77145.0;attach=175283;image';
        let tick_count = 0,
            rightPressed = false, //определение нажатых кнопак, изначальное значение false, так как кнопки не нажаты
            leftPressed = false,
            jackWidth = 34, //ширина, высота
            jackHeight = 89,
            sx = 0,
            dx = 100, //координаты
            dy = canvas.height - jackHeight - 15,
            jumpPressed = false,
            jumpCount = 0,
            jumpLength = 75,//длина прыжка по горизонтали
            jumpHeight = 0;//высота прыжка
        sprite.onload = function () { //отрисовка стоящего сузуки при загрузке, его стандартное состояние
            stayMan(dy);
        };

        function stayMan(y) {
            ctx.clearRect(0, 0, canvas.width, canvas.height);
            ctx.drawImage(sprite, 50, 178, 39, 89, dx, y, jackWidth, jackHeight);
        }

        function jumpMan() {
            ctx.clearRect(0, 0, canvas.width, canvas.height);
            ctx.drawImage(sprite, 0, 355, 57, 89, dx, dy - jumpHeight, 57, jackHeight);
        }

        function drawMan() { //отрисовка мальчика во время движения
            ctx.clearRect(0, 0, canvas.width, canvas.height);//очистка канваса
            sx = (sx === 510 ? 0 : sx + 34); //переброс в начало
            ctx.drawImage(sprite, sx, 0, 32, 89, dx, dy, jackWidth, jackHeight);//отображение первого спрайта
        }

        function forKeydown(e) {
            if (e.keyCode === 32) jumpPressed = true; //пробел
            if (e.keyCode === 37) leftPressed = true; //стрелочка лево
            if (e.keyCode === 39) rightPressed = true;//стрелочка право
        }

        function forKeyup(e) {
            if (e.keyCode === 37) {
                leftPressed = false;
                stayMan(dy);
            }
            if (e.keyCode === 39) {
                rightPressed = false;
                stayMan(dy);
            }
        }

        document.addEventListener('keydown', forKeydown, false);
        document.addEventListener('keyup', forKeyup, false);


        function moveMan() {
            if (rightPressed && dx < canvas.width - jackWidth) {
                tick();
                dx += 4
            }
            if (leftPressed && dx > 0) {
                tick();
                dx -= 4
            }
            if (jumpPressed) {
                jumpCount++;
                jumpHeight = 2 * jumpLength * Math.sin(Math.PI * jumpCount / jumpLength); //отнимается от dy, значит мальчик становится выше
                jumpMan();
            }

            if ((dx + 45 <= secondLineX)) {
                dy = canvas.height - jackHeight - 15;
            }
            if ((dx - 55 + jackWidth) >= (secondLineX + secondWidth)) {
                dy = canvas.height - jackHeight - 15;
            }
            //отрабатывает прыжок на блок!!!!!!!!!!!!!!!!!!!!!!!!
            if ((dy - jumpHeight + jackHeight <= thirdLineY) && ((dx + 45 >= secondLineX) && (dx - 45 + jackWidth) <= (secondLineX + secondWidth))) {
                if((dx + 45 <= secondLineX)){
                    dy = canvas.height - jackHeight - 15;
                }
                jumpCount = 0;
                jumpPressed = false;
                jumpHeight = -75;
                dy = thirdLineY - jackHeight + 15;
                stayMan(thirdLineY - jackHeight + 15);
                console.log('hi');
            }

            if (jumpCount > jumpLength) {
                jumpCount = 0;
                jumpPressed = false;
                jumpHeight = 0; //ничего не отнимается, значит возвращается в исходную позицию
                stayMan(dy);
            }
        }

        setInterval(moveMan, 10);

        function tick() {
            if (tick_count > 10) { //количвество отрисованных кадров, влияние на скорость
                tick_count = 0;
                drawMan(dy);
            }
            tick_count += 1;
        }
    }

    jack();
</script>
</body>
</html>

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
dollar, 2019-07-11
@dollar

You are counting new coordinates from the initial ones, but you need to read new coordinates from the previous ones.
If your game becomes more difficult, then this will help you a lot. For example, if there is a ceiling that you can hit against, then the jump will be interrupted and a free fall will begin.
That is, you need simple physics (known to you from school) - speed and acceleration . At the moment of the jump, there are only initial coordinates and a velocity vector . Everything. There is gravity as an acceleration (it always pulls down), plus you can enable custom acceleration with the keyboard arrows, or you can not allow it, depending on the gameplay.
Thus, as far as the block is concerned, at the time of the jump, there will simply be other initial coordinates. The jump function doesn't care what the coordinates are, it just sets the velocity vector if there is a surface to bounce off. Further calculation of the movement is no longer a problem of the jump function, but of other functions.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question