Pavel Kostadinov
Pavel Kostadinov

Reputation: 13

How do can i apply different forces using vectors?

I am trying to make a simple side-scroller game in p5.js. As far as I understood I need to have vectors to imitate real-world physics. All I really need is a force that pushed the player down and a force that makes it jump when a key is pressed. I watched a video from youtube on the topic and I am pretty sure I followed it exactly as it was described but I get a different result. My keys don't always get detected and also they are all with different amount of force. Thank you in advance.

// This is a part of a player class that I have
update(){
  this.pos.add(this.vel)
  this.vel.add(this.acc)
}

applyForce(force){
  this.vel.add(force)
}

earth(){
  if (this.pos.y > height - 100){
    this.pos.y = height - 100
    this.acc.y *= 0
  }
}

// This is where I detect the pressed key
function keyPressed(){
  let jump = createVector(0,-10)
  player.applyForce(jump)
}

// And then in the draw function i have this
player.applyForce(gravity)
player.earth()

Upvotes: 1

Views: 411

Answers (1)

meowgoesthedog
meowgoesthedog

Reputation: 15035

Basic problems:

  • applyForce should add the force vector to the acceleration, not the velocity.
  • You should not update the physics in the draw function, but in update.
  • In games the jumping mechanic is typically implemented as an impulse (i.e. velocity change) instead of a force. You could add an applyImpulse function for this.
  • You should always reset the acceleration after updating, so that forces don't accumulate.

Amended code:

// move all updates to here
update(){
  this.acc.add(gravity)
  this.pos.add(this.vel)
  this.vel.add(this.acc)

  this.earth()

  this.acc = createVector(0, 0)
}

// add to acceleration, not velocity
applyForce(force){
  this.acc.add(force)
}

// impulse for jumping
applyImpulse(imp){
  this.vel.add(imp)
}

// set vertical *velocity* to zero, not acceleration
earth(){
  if (this.pos.y > height - 100){
    this.pos.y = height - 100
    this.vel.y = 0
  }
}

// apply the impulse to jump
function keyPressed(){
  let jump = createVector(0,-10)
  player.applyImpulse(jump)
}

// no updating in the draw function

Upvotes: 1

Related Questions