HTML5画布字符跳转

HTML5 canvas character jump

本文关键字:字符 布字符 HTML5      更新时间:2023-09-26

我试着通过阅读这个教程来制作一个动画角色:http://mrbool.com/html5-canvas-moving-a-character-with-sprites/26239。让角色向左移动很容易("向右移动"已经完成了)。但是如何让角色跳跃呢?我在想这样的事情:

    case 38:
        if (y + dy > HEIGHT){
            y += dy
        } 
    break;

…但它只是让角色向上移动(没有动画)。有人能帮帮我吗?下面是一些有用的代码示例

你会得到这样的跳跃行为(使用教程中相同的代码)

JSFiddle

var canvas;// the canvas element which will draw on
var ctx;// the "context" of the canvas that will be used (2D or 3D)
var dx = 50;// the rate of change (speed) horizontal object
var x = 30;// horizontal position of the object (with initial value)
var y = 150;// vertical position of the object (with initial value)
var limit = 10; //jump limit
var jump_y = y;
var WIDTH = 1000;// width of the rectangular area
var HEIGHT = 340;// height of the rectangular area
var tile1 = new Image ();// Image to be loaded and drawn on canvas
var posicao = 0;// display the current position of the character
var NUM_POSICOES = 6;// Number of images that make up the movement
var goingDown = false;
var jumping;
function KeyDown(evt){
    switch (evt.keyCode) {
        case 39:  /* Arrow to the right */
            if (x + dx < WIDTH){
                x += dx;
                posicao++;
                if(posicao == NUM_POSICOES)
                    posicao = 1;
                Update();
            }
            break;    
        case 38:
            jumping = setInterval(Jump, 100);
    }
}
function Draw() {      
    ctx.font="20px Georgia";
    ctx.beginPath();
    ctx.fillStyle = "red";   
    ctx.beginPath();
    ctx.rect(x, y, 10, 10);
    ctx.closePath();
    ctx.fill();   
    console.log(posicao);
}
function LimparTela() {
    ctx.fillStyle = "rgb(233,233,233)";   
    ctx.beginPath();
    ctx.rect(0, 0, WIDTH, HEIGHT);
    ctx.closePath();
    ctx.fill();   
}
function Update() {
    LimparTela();    
    Draw();
}
var Jump = function(){
    if(y > limit && !goingDown){
        y-=10;
        console.log('jumping: ' + y);
    } else{
    goingDown = true;
        y +=10;
        if(y > jump_y){
            clearInterval(jumping);
            goingDown = false;
        }
    }
}
function Start() {
    canvas = document.getElementById("canvas");
    ctx = canvas.getContext("2d");
    return setInterval(Update, 100);
}
window.addEventListener('keydown', KeyDown);
Start();

这个问题没有一个正确的答案,除非你找到一个游戏设计库,否则也没有一个简单的答案。你的问题在于你是在根据输入即时移动角色,但跳跃需要随时间移动。你必须找到一个移动的精灵库——我没有一个特别推荐,但我相信谷歌有几个——或者自己设置一些东西,每隔几毫秒运行一次,更新角色的位置和某种速度变量。

编辑:看那个教程,想到的最简单的解决方案是把你的动画代码里面的Update(),像这样:

function Update() {
    LimparTela();
    Animate();
    Draw();
}

Animate()内部,你应该跟踪角色的高度和垂直动量。如果动量是正的,增加一点y位置,否则减少一点。无论哪种方式,都要减少一些动量。添加一些东西来防止角色穿过地板,并让向上键设置角色在地板上时的动量为正。

请注意,这是一个非常简单的解决方案,但对于基本教程来说,它可以完成工作。