Skip to content
Advertisement

How to use windowWidth and windowHeight outside of setup()?

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):

function setup() {
    createCanvas(windowWidth, windowHeight);
}

var x = 0;
var y = 0;
var speed = 5;
var laserSpeed = 10;
var laserY = 0;
var laserX = Xwidth;

function draw() {
    background(230);
    //changing x and y var according to keys pressed
    if(keyIsPressed) { 
        if (key.toString() === "a") {
           x -= speed;
        } 
        if (key.toString() === "w") {
            y -= speed;
        } 
        if (key.toString() === "d") {
            x += speed;
        } 
        if (key.toString() === "s") {
            y += speed;
        }
    }
    if(laserX >= width) {
        laserY = random(0, height);
    } 
    else {
        laserX += laserSpeed;
    }

    rect(laserX, laserY, 100, 20);
  
    //player
    rect(x, y, 20, 20);
}

Advertisement

Answer

If you use global variables like WIDTH and HEIGHT it will allow you to use them from anywhere in the code.

let WIDTH;
let HEIGHT;

function setup() { 
  WIDTH = windowWidth;
  HEIGHT = windowHeight;
  createCanvas(WIDTH, HEIGHT);
}
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement