用Java语言制作游戏角色角色

时间:2018-10-03 08:56:45

标签: javascript html game-development

我正在尝试制作一个带有行走角色的简单游戏。当我按下一个按钮时,我想在两个图像之间连续切换(按住该按钮时),这将使角色看起来好像在移动。它确实会移动,但是图片之间的切换在开始时仅发生一次。谁能告诉我我在做什么错?或建议一种方法。坚持了几个小时。

任何帮助将不胜感激。

<!DOCTYPE html>
<html>
<head>
    <link href="./styles/style.css" rel="stylesheet" type="text/css"><link>
    <meta charset="utf-8" />
    <title>Playa Haters</title>
    <style>
    	* { padding: 0; margin: 0; }
    </style>
</head>
<body>

<canvas id="myCanvas" width="800" height="450"></canvas>
<img id="step1" src="media/step1.jpg" width="120" height="150">
<img id="step2" src="media/step2.jpg" width="120" height="150">

<script>
    var canvas = document.getElementById("myCanvas");
    var ctx = canvas.getContext("2d");  //get content 

    var step1 = document.getElementById("step1");
    var step2 = document.getElementById("step2");
    var currentStep =  step1;

    document.addEventListener("keydown", keyDownHandler, false);
    document.addEventListener("keyup", keyUpHandler, false);
    
    var rightPressed = false;
    var leftPressed = false;
    var step = 5;
    var distance = null;

    function keyDownHandler(e) {
        if(e.keyCode == 39){
            rightPressed = true;
        }
        else if(e.keyCode = 37){
            leftPressed = true;
        }
    }

    function keyUpHandler(e) {
    if(e.keyCode == 39) {
        rightPressed = false;
    }
    else if(e.keyCode == 37) {
        leftPressed = false;
        }
    }

    //initial position
    var x = canvas.width/2;
    var y = canvas.height/2 - 100;

    function drawShooter(){
        ctx.drawImage(currentStep, x, y);
    }

    function walk(){
        if (currentStep = step1){
            currentStep = step2;
        }
        else if (currentStep = step2){
            currentStep = step1;
        }
    }

    function draw(){
        ctx.clearRect(0, 0, canvas.width, canvas.height); 
        drawShooter();
        if(rightPressed) {
        x += step;
        setInterval(walk, 500);
        } 
        else if(leftPressed) {
        x -= step;
        setInterval(walk, 500);
        } 
    }

    setInterval(draw, 20);

</script>

</body>
</html>

1 个答案:

答案 0 :(得分:1)

在walk函数中,您正在分配而不是在if语句中进行比较...您拥有:

function walk(){
    if (currentStep = step1){
        currentStep = step2;
    }
    else if (currentStep = step2){
        currentStep = step1;
    }
}

您应该改为:

function walk(){
    if (currentStep === step1){
        currentStep = step2;
    }
    else if (currentStep === step2){
        currentStep = step1;
    }
}

请注意条件内的三元组等于。这应该可以解决交换图像的问题。