Phaser3 Sprite is not defined?

Hi, this is probably a dumb question, but I am trying to create a sprite and can’t figure out the syntax for it…

According to the docs here (https://photonstorm.github.io/phaser3-docs/Phaser.GameObjects.Sprite.html#Sprite__anchor) I should be able to call “new Sprite”, but where does Sprite come from?

I tried importing it from phaser

import { Sprite } from 'phaser'

and also tried using “Phaser.Sprite”, but I always get errors that Sprite is not defined :thinking:

I was able to create a sprite with

this.physics.add.sprite

but I’m still not sure if this is a hack or the actual proper way to create sprites in phaser3.

It would be great if there was an “examples” section in the docs, something like clojure’s docs! (https://clojuredocs.org/clojure.core.async/chan)

Maybe these phaser docs are generated from the source code? It just seems very confusing to me to have “new Sprite(scene, x, y, texture [, frame])” in big bold letters in the docs if that is not how you are supposed to create sprites as a user of the library. :grin:

If Phaser is available as a global, the constructor is new Phaser.GameObjects.Sprite, which is shown at the top of the documentation page. When you create a sprite this way, you need to give it the scene and manually add it to its display and update list - which you can either do directly by through this.children and this.sys.updateList, or by letting Phaser do it with this.add.existing.

this.physics.add.sprite creates an ArcadeSprite, which is a regular Sprite with an some additional methods and an automatically added body.

There is no “proper” way to create a sprite in Phaser 3. this.add.sprite simply creates a Sprite object and adds it to the scene’s systems. Using the Sprite constructor can accomplish the same goal, it’s just a “lower-level” operation. Personally, I’d recommend sticking to this.add unless you’re creating your own class. Even then, use this.add.existing to add it and don’t use the scene systems directly. Some of the methods in the Game Object Factory (this.add) contain checks to make sure that you don’t crash the game by adding an object to a list in which it doesn’t belong.

It takes some time to get used to the API docs (and I’ve found that in some cases it’s easier to read the source code directly). If it interests you, a community member called rex has created notes on some of the API, which are often clearer than the formal documentation.

1 Like

You’ll probably find it easier to start with the examples, e.g. game-objects/sprites or physics/arcade, rather than the API docs.

2 Likes

For ES6 importing, to get at Sprite you need to extract it from GameObjects, like so:

import {GameObjects} from 'phaser';
const {Sprite} = GameObjects;
1 Like

thanks! I will check them out. :+1:

and thanks for clarifying the import @saricden

:heart: np!

1 Like