S
S
sljfhwo2019-10-22 12:13:02
JavaScript
sljfhwo, 2019-10-22 12:13:02

The player is not visible in js why huh?

Why is the player not visible, I tried everything, I can’t see him at all, what to do, I can’t think of anything anymore, it doesn’t work at all

<!DOCTYPE html>
<html>
<head>
  <title>Game</title>
</head>
<body>
    <canvas id = "canvas" width = "355" height = "366"></canvas>
    <style type="text/css">
    	canvas{
    		border: 4px black solid;
    	}
    </style>
  <script type="text/javascript">
document.getElementById("canvas");
var ctx = canvas.getContext("2d");
x = 35
y = 234
uppress = 0
downpress = 0
leftpress = 0
rightpress = 0
function player(){
document.addEventListener("keydown", function(e){
if(e.keyCode == 87){
uppress = 1
}

if(e.keyCode == 83){
downpress = 1 
}

if(e.keyCode == 65){
leftpress = 1
}

if(e.keyCode == 68){
rightpress = 1
}
})

document.addEventListener("keyup", function(e){
if(e.keyCode == 87){
uppress = 0
}

if(e.keyCode == 83){
downpress = 0 
}

if(e.keyCode == 65){
leftpress = 0
}
if(e.keyCode == 68){
rightpress = 0
}
})

if(uppress = 1){
y-=1
}

if(downpress = 1){
y+=1
}

if(leftpress = 1){
x-=1
}

if(rightpress = 1){
x+=1
}
}
function game(){
ctx.clearRect(0,0,355,366);
ctx.fillRect(x, y, 32, 32);
player();
}
setInterval(game, 20);

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Afanasy Zakharov, 2019-10-22
@afanasiyz

You didn't call the game function.

D
dollar, 2019-10-22
@dollar

Because you are new to topics like JavaScript and HTML.
The tag <script>must be closed with the tag </script>, the rest is not so critical.
Judging by the fact that the HTML code is formatted, but the JS is not, you copied this "game" from somewhere on the Internet and are just trying to run it.
Better try not to run the finished script, but write it yourself in small steps. First, a script like Hello World, then a script that reacts in the simplest way to a single key (in the future it will be a control system), and so on. That way you can understand what's going on. Otherwise, any bug will cause stupor and misunderstanding, and a desire to seek help from the Toaster.
In addition, when you make a small change and your script stops working, you will even understand where your error is without debugging. Obviously, in the changes you made last. If you added one line of code, then that's the problem. Or maybe not in it, but if you remove it, then there will be no problem. In any case, finding the error is easier.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question