I need the screen dimensions for a project, but trying windowWidth and windowHeight yields an error saying I can’t use them outside of setup(). I also tried defining the windowWidth and Height to a new constant, but it simply says the constant has not been defined.
Here’s the current state of my code (doesn’t work, but gives a pretty good idea of the code):
JavaScript
x
41
41
1
function setup() {
2
createCanvas(windowWidth, windowHeight);
3
}
4
5
var x = 0;
6
var y = 0;
7
var speed = 5;
8
var laserSpeed = 10;
9
var laserY = 0;
10
var laserX = Xwidth;
11
12
function draw() {
13
background(230);
14
//changing x and y var according to keys pressed
15
if(keyIsPressed) {
16
if (key.toString() === "a") {
17
x -= speed;
18
}
19
if (key.toString() === "w") {
20
y -= speed;
21
}
22
if (key.toString() === "d") {
23
x += speed;
24
}
25
if (key.toString() === "s") {
26
y += speed;
27
}
28
}
29
if(laserX >= width) {
30
laserY = random(0, height);
31
}
32
else {
33
laserX += laserSpeed;
34
}
35
36
rect(laserX, laserY, 100, 20);
37
38
//player
39
rect(x, y, 20, 20);
40
}
41
Advertisement
Answer
If you use global variables like WIDTH and HEIGHT it will allow you to use them from anywhere in the code.
JavaScript
1
9
1
let WIDTH;
2
let HEIGHT;
3
4
function setup() {
5
WIDTH = windowWidth;
6
HEIGHT = windowHeight;
7
createCanvas(WIDTH, HEIGHT);
8
}
9