How can I make an object jump once until it touches land/ground in Kaboom.js

262 Views Asked by At
import kaboom from "kaboom"

const SPEED = 300
const JUMP_FORCE = 500
const GRAVITY_AMOUNT = 1000

// initialize context
kaboom({
    background: "#000"
})



// load assets
loadSprite("player", "sprites/player.png")
loadSprite("spider", "sprites/spider.png")
loadSprite("floor", "sprites/floor.png")

gravity(GRAVITY_AMOUNT)


const player = add([
    sprite("player"),
    pos(250, height() - 100),
    area(),
    body()
])


const grass = add([
    rect(width(), 16),
    pos(0, height() - 64),
    area(),
    solid(),
    color(60, 21, 176)
])

const land = add([
    rect(width(), 48),
    pos(0, height() - 48),
    area(),
    solid(),
    color(14, 15, 97)
])

onKeyPress("space", () => {
    player.jump(JUMP_FORCE)
})

onKeyDown("a", () => {
    player.move(-SPEED, 0)
})
onKeyDown("d", () => {
    player.move(SPEED, 0)
})

var floor = add([
    sprite("floor"),
    scale(0.5),
    pos(120, height() - 150),
    area(),
    z(-1)
])

action(() => {
    if(player.pos.y < height() - floor.height){
        floor.use(body())
    }
})

onMouseDown(() => {
    player.jump(JUMP_FORCE)
})

onTouchStart(() => {
    player.jump(JUMP_FORCE)
})

So this is my game source code which I wrote in Kaboom.js I want to make the jump event only while the player is on land. Not jump again in air. I do appreciate if someone help me about this as I am new at Kaboom.js

.................................................................................................

1

There are 1 best solutions below

0
CaptainCookie15 On BEST ANSWER

For your problem, I would suggest using:

player.isGrounded()

which returns if the player is touching the ground or not.

For example:

onKeyPress("space", () => {
  if(player.isGrounded()) {
    player.jump(JUMP_FORCE)
  }
})

Hope this helped with your problem!