Extra
Common Patterns

Common Patterns

Disabling the default character controller

Dreamlab’s built-in 2D platformer controller is a special entity that is automatically initialized. To disable it, you can use the code below. This snippet is already included in any template that overrides the default character controller.

shared.ts
import { disableDefaultPlatformController } from './util.ts'
export const sharedInit: InitShared = game => {
  // disable default character controller
  disableDefaultPlatformController()
}
client.ts
import { setDefaultPlayerCameraTarget } from './util.ts'
 
// if you want to have the camera automatically track your custom controller, you can do use the following pattern
const player = game.spawn({
  // ...
}) as MyCustomPlayerController
 
const camera = game.client.render.camera
setDefaultPlayerCameraTarget(player)
util.ts
import { SpawnableEntity } from '@dreamlab.gg/core'
import { Player, isNetPlayer, isPlayer } from '@dreamlab.gg/core/entities'
import { game } from '@dreamlab.gg/core/labs'
 
export const disableDefaultPlatformController = () => {
  const server = game('server')
  const client = game('client')
  if (server) {
    server.events.common.addListener('onInstantiate', entity => {
      if (isNetPlayer(entity)) {
        entity.body.isSensor = true
      }
    })
  }
  if (client) {
    client.events.common.addListener('onInstantiate', entity => {
      if (isNetPlayer(entity)) client.destroy(entity)
      if (isPlayer(entity)) {
        client.destroy(entity)
        Player.unregisterInputs()
      }
    })
  }
}
 
export const setDefaultPlayerCameraTarget = (e: SpawnableEntity) => {
  const camera = game('client')?.client.render.camera
  if (!camera) return
 
  camera.target = e
  camera.defaultPlayerEntity = e
  game('client')?.events.common.addListener('onInstantiate', entity => {
    // if a default player entity spawns, reset the target back to ours
    if (isPlayer(entity)) {
      camera.target = e
      // defaultPlayerEntity defines the entity that's automatically moved when you pan in the level editor
      camera.defaultPlayerEntity = e
    }
  })
}
This docs page is under construction. Expect more information coming to this page soon!
If you have questions, please ask them in our Discord server and we'll answer them promptly! 😊