Reputation: 11
I'm trying to make a simple game with a walking character. When a button is pressed down i want to continuously switch between two images (while the button is held down) which will make it look like the character is moving. It does move, however the switch between pictures happens only once at the beginning. Can anyone tell me what am i doing wrong? Or suggest a way to do it. Been stuck on this for hours.
Any help will be much appreciated.
<!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>
Upvotes: 1
Views: 1846
Reputation: 431
On your walk function you are assigning instead of comparing inside the if statement... you have:
function walk(){
if (currentStep = step1){
currentStep = step2;
}
else if (currentStep = step2){
currentStep = step1;
}
}
You should have instead:
function walk(){
if (currentStep === step1){
currentStep = step2;
}
else if (currentStep === step2){
currentStep = step1;
}
}
Note the triple equals inside the conditional. This should solve the problem with swapping the images.
Upvotes: 1