1

I want to create an "organizer" game where the player needs to drag-and-drop sprites into a rectangle or a circular sprite.

I tried to use container.onCollision('correspondingsprite', (css)=>{destroy(css)}, however, this didn't work. When I removed the drag-and-drop and added in key response for movement, it worked.

(1) How can I make this work with drag and drop and (2) why didn't it work before? This is my original code:

import kaboom from "kaboom"

kaboom()

loadSprite("crewmate", "/sprites/crewmate.png")
loadSprite("imposter", "/sprites/imposter.png")
loadSprite("bean", "/sprites/bean.png")

// the object that is being dragged
let drag_obj = null
// custom component
function drag() {
  return {
    id: "drag", // the name
    require: [ "pos", "area", ], // needs pos and area to work
    // what happens when used in add()
    add() {
      // when clicked, let the dragged object be this
      this.onClick(() => {
        if (drag_obj) {
          return
        }
        drag_obj = this
        offset = mousePos().sub(this.pos)
        // remove and re-add object so it moves to top
        readd(this)
      })
    },
    // what happends when screen updated
    update() {
      // if this obj is being dragged
      if (drag_obj === this) {
        // new position
        cursor("move")
        this.pos = mousePos()
      }
    },
  }

}
// when mouse is released, nothing is being dragged
onMouseRelease(() => {drag_obj = null})

function spawnAstro() {
  seed = rand(0, 100)
  if (seed < 80){
    add([
      sprite("crewmate"),
      pos(rand(width()+10), rand(height())),
      area(),
      origin("center"),
      drag(),
      "crewimg"
    ]);
  } else if (seed < 95) {
    add([
      sprite("imposter"),
      pos(rand(width()+10), rand(height())),
      area(),
      origin("center"),
      drag(),
      "impostimg"
    ]);
  } else {
    add([
      sprite("bean"),
      pos(rand(width()+10), rand(height())),
      area(),
      origin("center"),
      drag(),
      "beanimg"
    ]);
  }

  wait(rand(2.5, 3), ()=>{spawnAstro()});
}
spawnAstro();

// add containers
const crew = add([
  rect(250, 250),
  pos(10,10),
  color(57, 204, 204),
  area()
])
crew.onCollide("crewimg", (c) => {
    destroy(c)
})

const impost = add([
  rect(250, 250),
  pos(10,270),
  color(204, 57, 57),
  area()
])
impost.onCollide("impostimg", (i) => {
    destroy(i)
})

const bean = add([
  rect(250, 250),
  pos(10,530),
  color(217, 43, 171),
  area()
])
bean.onCollide("beanimg", (by) => {
    destroy(b)
})

0 Answers0