jnsmalm / pixi3d

The 3D renderer for PixiJS. Seamless integration with 2D applications.
https://pixi3d.org
MIT License
759 stars 44 forks source link

How to get and control main camera? #26

Closed FlokiTV closed 3 years ago

FlokiTV commented 3 years ago

Hi, I'm working on fake 3D and sprite stacks with GDevelop (Game engine with pixi as core) I'm trying put some 3D object on canvas, just a cube to follow a 2D cube I create a cube and put as child of 2D, but when I move a scene, the 3D camera stucks I try create a new Camera() for renderer but when I update positions nothing happens

Imgur

this is possible?

jnsmalm commented 3 years ago

Hello @FlokiTV

Yes, this is possible by converting the screen coords of the sprite to world coords. See example below. The reason it's not working when you add a 3D object as a child of a 2D is object is intentional. In your case when you want to have both 2D and 3D object in same screen position it makes sense, but in many other cases it doesn't make sense (from a general point of view as a library) for it to behave like that as default.

let app = new PIXI.Application({
  backgroundColor: 0xdddddd, resizeTo: window, antialias: true
})

document.body.appendChild(app.view)

let distanceFromCamera = 15

let sprite = app.stage.addChild(new PIXI.Sprite(PIXI.Texture.WHITE))
sprite.position.set(300, 300)
sprite.scale.set(10)
sprite.anchor.set(0.5)

document.onmousemove = event => {
  // Move sprite to cursor position
  sprite.position.set(event.screenX, event.screenY)
  followSprite()
}

let followSprite = () => {
  // Convert screen coords to world coords
  mesh.position = PIXI3D.Camera.main.screenToWorld(sprite.x, sprite.y, distanceFromCamera)
}

let mesh = app.stage.addChild(PIXI3D.Mesh3D.createCube())
followSprite()

let light = Object.assign(new PIXI3D.Light(), {
  x: -1,
  z: -5,
})
PIXI3D.LightingEnvironment.main.lights.push(light)

let rotation = 0
app.ticker.add(() => {
  mesh.rotationQuaternion.setEulerAngles(0, rotation++, 0)
})
FlokiTV commented 3 years ago

Thanks for your time! I'll try again