4

I'm working on a basic first person camera controller in p5.JS, and I'm using the move function inside of an if statement (uses keyIsDown) and it still moves the camera when the key isn't pressed (I mean like its down for a second then no longer pressed).

I've also tried using while () but that crashes it.

let d;
let cam;
let x, y, z;
let img;
let floor_texture;
//place holder image    
floor_texture = 'https://miro.medium.com/max/1400/1*WI5Zw1eKEKNmRX3zreeUHw.png';

function preload() {
  img = loadImage(floor_texture);
}

function setup() {
  createCanvas(windowWidth, windowHeight, WEBGL);
  x = 0;
  y = 0;
  z = 0;
  cam = createCamera();
}

function draw() {
  d = dist
  background(255);
  cam.pan(-movedX * 0.005);
  cam.tilt(movedY * 0.005);
  fill('white');
  sphere(25);
  fill('red');
  texture(img);
  translate(0, 350, 0)
  box(5000, 500, 5000)
  if (keyIsPressed && keyCode === 69) {
    requestPointerLock();
  }
  cam.move(x, y, z);
  if (keyIsDown(87)) {
    z -= 0.1;
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.1/p5.js"></script>
ggorlen
  • 44,755
  • 7
  • 76
  • 106

3 Answers3

3

It's because you don't set a new z every time keyIsDown(87), but you cam.move with z as the argument.

So something like:

z = 0;
cam.move(x,y,z); //here z = 0, so it doesn't move.
z -= 0.1; 
cam.move(x,y,z); //here z = -0.1, so it moves, even if keyIsDown isn't true anymore.

Every time keyIsDown(87) is true, it just increases the speed at which cam moves.

If you want to set the z position like that, you would have to find a way to set camera position, instead of move it.

Or you could do something like:

draw() {
...



if (keyIsDown(87)) {
  dz = -0.1;
} else {
  dz = 0;
}

cam.move(dx,dy,dz)
...
}
cSharp
  • 2,884
  • 1
  • 6
  • 23
2

A more accurate name for x, y and z would be velocityX, velocityY and velocityZ. This is because you're adding -0.1 to z each frame if a button is pressed. z is then added to the camera's position. So in this case, we should reset z to 0 after the camera is moved.

if (keyIsDown(87)) {
  z -= 0.1;
}
cam.move(x, y, z);
z = 0;
Lachie
  • 45
  • 5
1

In this case, you are subtracting from z (your velocity) on every tick while key 87 (W) is pressed.

Currently, this value never gets reset when you release the key.

If you want the user to have a constant speed while holding down the key, pass a constant value when the key is pressed (and 0 otherwise) instead of z when calling cam.move.

If you want the user to accelerate when holding down the key (as they currently do), you'll have to add a way to return them back to a z of 0 speed when the key is not pressed.

John Paul R
  • 649
  • 5
  • 10