class FlxSprite
package flixel
extends FlxObject › FlxBasic
extended by FlxShape, FlxBackdrop, FlxExtendedMouseSprite, FlxNestedSprite, FlxPieDial, FlxSpriteAniRot, FlxSpine, FlxEffectSprite, FlxClothSprite, FlxSkewedSprite, FlxTrailArea, FlxNapeSprite, FlxTransitionSprite, FlxUIRegion, FlxUISprite, FlxBullet, FlxParticle, FlxTypedSpriteGroup, FlxBGSprite, FlxBitmapText, FlxText, FlxTileblock, FlxBar, FlxTypedButton, FlxStrip
The core building blocks of all Flixel games. With helpful tools for animation, movement and features for the needs of most games.
It is pretty common place to extend FlxSprite
for your own game's needs; for example a SpaceShip
class may extend FlxSprite
but could have additional variables for the game like shieldStrength
or shieldPower
.
Collision and Motion
Flixel handles many aspects of collision and physics motions for you. This is all defined in the
base class: FlxObject, check there for things
like: x
, y
, width
, height
, velocity
, acceleration
, maxVelocity
, drag
, angle
,
and angularVelocity
. All of these affect the movement and orientation of the sprite as well
as FlxG.collide and
FlxG.overlap
Graphics
FlxSprites
are just FlxObjects
with the ability to show graphics. There are various ways to do this.
loadGraphic()
Snippets - Loading Sprites The easiest way to use a single image for your FlxSprite. Using the OpenFL asset system defined in the project xml file you simply have to define a path to your image and the compiler will do the rest.
var player = new FlxSprite();
player.loadGraphic("assets/player.png");
add(player);
Animations
Snippets - Animations
When loading a graphic for a FlxSprite
, you can specify is as an animated graphic. Then, using
animation, you can setup animations and play them.
// sprite's graphic will be loaded from 'path/to/image.png' and is set to allow animations.
sprite.loadGraphic('path/to/image/png', true);
// add an animation named 'run' to sprite, using the specified frames
sprite.animation.add('run', [0, 1, 2, 1]);
// play the 'run' animation
sprite.animation.play('run');
makeGraphic()
Snippets - Loading Sprites This method is a handy way to make a simple color fill to quickly test a feature or have the basic shape.
var whiteSquare = new FlxSprite();
whiteSquare.makeGraphic(200, 200, FlxColor.WHITE);
add(whiteSquare);
Properties
Position: x, y
whiteSquare.x = 100;
whiteSquare.y = 300;
Size: width, height
Automatically set in loadGraphic() or makeGraphic(), changing this will only affect the hitbox of this sprite, use scale to change the graphic's size.
// get
var getWidth = whiteSquare.width;
// set
whiteSquare.width = 100;
whiteSquare.height = 100;
Scale
Snippets - Scale (FlxPoint) Change the size of your sprite's graphic. NOTE: The hitbox is not automatically adjusted, use updateHitbox() for that.
// twice as big
whiteSquare.scale.set(2, 2);
// 50%
whiteSquare.scale.set(0.5, 0.5);
Offset
(FlxPoint) Controls the position of the sprite's hitbox. Likely needs to be adjusted after changing a sprite's width, height or scale.
whiteSquare.offset.set(50, 50);
Origin
(FlxPoint) Rotation axis. Default: center.
WARNING: If you change this, the visuals and the collisions will likely be pretty out-of-sync if you do any rotation.
// rotate from top-left corner instead of center
whiteSquare.origin.set(0, 0);
Static variables
staticdefaultAntialiasing:Bool = false
The default value for antialiasing
across all FlxSprites
,
defaults to false
.
5.0.0
.Constructor
new(X:Float = 0, Y:Float = 0, ?SimpleGraphic:Null<FlxGraphicAsset>)
Creates a FlxSprite
at a specified position with a specified one-frame graphic.
If none is provided, a 16x16 image of the HaxeFlixel logo is used.
Parameters:
X | The initial X position of the sprite. |
---|---|
Y | The initial Y position of the sprite. |
SimpleGraphic | The graphic you want to display (OPTIONAL - for simple stuff only, do NOT use for animated images!). |
Variables
alpha:Float = 1.0
Set alpha to a number between 0
and 1
to change the opacity of the sprite.
See also:
animation:FlxAnimationController
Class that handles adding and playing animations on this sprite.
See also:
antialiasing:Bool = defaultAntialiasing
Controls whether the object is smoothed when rotated, affects performance.
read onlybakedRotationAngle:Float = 0
The minimum angle (out of 360°) for which a new baked rotation exists. Example: 90
means there
are 4 baked rotations in the spritesheet. 0
if this sprite does not have any baked rotations.
See also:
clipRect:FlxRect
Clipping rectangle for this sprite.
Changing the rect's properties directly doesn't have any effect,
reassign the property to update it (sprite.clipRect = sprite.clipRect;
).
Set to null
to discard graphic frame clipping.
color:FlxColor = 0xffffff
Tints the whole sprite to a color (0xRRGGBB
format) - similar to OpenGL vertex colors. You can use
0xAARRGGBB
colors, but the alpha value will simply be ignored. To change the opacity use alpha
.
See also:
dirty:Bool = true
Set this flag to true to force the sprite to update during the draw()
call.
NOTE: Rarely if ever necessary, most sprite operations will flip this flag automatically.
facing:FlxDirectionFlags = RIGHT
Can be set to LEFT
, RIGHT
, UP
, and DOWN
to take advantage
of flipped sprites and/or just track player orientation more easily.
See also:
read onlyframeHeight:Int = 0
The height of the actual graphic or image being displayed (not necessarily the game object/bounding box).
framePixels:BitmapData
The current display state of the sprite including current animation frame,
tint, flip etc... may be null
unless useFramePixels
is true
.
read onlyframeWidth:Int = 0
The width of the actual graphic or image being displayed (not necessarily the game object/bounding box).
read onlynumFrames:Int
The total number of frames in this image. WARNING: assumes each row in the sprite sheet is full!
read onlyoffset:FlxPoint
The position of the sprite's graphic relative to its hitbox. For example, offset.x = 10;
will
show the graphic 10 pixels left of the hitbox. Likely needs to be adjusted after changing a sprite's
width
, height
or scale
.
read onlyorigin:FlxPoint
WARNING: The origin
of the sprite will default to its center. If you change this,
the visuals and the collisions will likely be pretty out-of-sync if you do any rotation.
pixels:BitmapData
This sprite's graphic / BitmapData
object.
Automatically adjusts graphic size and render helpers if changed.
read onlyscale:FlxPoint
Change the size of your sprite's graphic.
NOTE: The hitbox is not automatically adjusted, use updateHitbox()
for that.
WARNING: With FlxG.renderBlit
, scaling sprites decreases rendering performance by a factor of about x10!
See also:
shader:FlxShader
GLSL shader for this sprite. Avoid changing it frequently as this is a costly operation.
4.1.0
.read onlyuseColorTransform:Bool = false
Whether or not to use a ColorTransform
set via setColorTransform()
.
useFramePixels:Bool = true
Always true
on FlxG.renderBlit
. On FlxG.renderTile
it determines whether
framePixels
is used and defaults to false
for performance reasons.
Methods
centerOffsets(AdjustPosition:Bool = false):Void
Helper function that adjusts the offset automatically to center the bounding box within the graphic.
Parameters:
AdjustPosition | Adjusts the actual X and Y position just once to match the offset change. |
---|
inlinecenterOrigin():Void
Sets the sprite's origin to its center - useful after adjusting
scale
to make sure rotations work as expected.
destroy():Void
WARNING: A destroyed FlxBasic
can't be used anymore.
It may even cause crashes if it is still part of a group or state.
You may want to use kill()
instead if you want to disable the object temporarily only and revive()
it later.
This function is usually not called manually (Flixel calls it automatically during state switches for all add()
ed objects).
Override this function to null
out variables manually or call destroy()
on class members if necessary.
Don't forget to call super.destroy()
!
draw():Void
Called by game loop, updates then blits or renders current frame of animation to the screen.
drawFrame(Force:Bool = false):Void
Request (or force) that the sprite update the frame before rendering. Useful if you are doing procedural generation or other weirdness!
Parameters:
Force | Force the frame to redraw, even if its not flagged as necessary. |
---|
getGraphicMidpoint(?point:FlxPoint):FlxPoint
getPixelAt(worldPoint:FlxPoint, ?camera:FlxCamera):Null<FlxColor>
Determines which of this sprite's pixels are at the specified world coordinate, if any.
Factors in scale
, angle
, offset
, origin
, and scrollFactor
.
Parameters:
worldPoint | The point in world space |
---|---|
camera | The camera, used for |
Returns:
a FlxColor
, if the point is in the sprite's graphic, otherwise null
is returned.
5.0.0
.getPixelAtScreen(screenPoint:FlxPoint, ?camera:FlxCamera):Null<FlxColor>
Determines which of this sprite's pixels are at the specified screen coordinate, if any.
Factors in scale
, angle
, offset
, origin
, and scrollFactor
.
Parameters:
screenPoint | The point in screen space |
---|---|
camera | The desired "screen" coordinate space. If |
Returns:
a FlxColor
, if the point is in the sprite's graphic, otherwise null
is returned.
5.0.0
.getRotatedBounds(?newRect:FlxRect):FlxRect
Calculates the smallest globally aligned bounding box that encompasses this
sprite's width and height, at its current rotation.
Note, if called on a FlxSprite
, the origin is used, but scale and offset are ignored.
Use getScreenBounds
to use these properties.
Parameters:
newRect | The optional output |
---|
Returns:
A globally aligned FlxRect
that fully contains the input object's width and height.
4.11.0
.getScreenBounds(?newRect:FlxRect, ?camera:FlxCamera):FlxRect
Calculates the smallest globally aligned bounding box that encompasses this sprite's graphic as it would be displayed. Honors scrollFactor, rotation, scale, offset and origin.
Parameters:
newRect | Optional output |
---|---|
camera | Optional camera used for scrollFactor, if null |
Returns:
A globally aligned FlxRect
that fully contains the input sprite.
4.11.0
.graphicLoaded():Void
Called whenever a new graphic is loaded for this sprite (after loadGraphic()
, makeGraphic()
etc).
isOnScreen(?camera:FlxCamera):Bool
Check and see if this object is currently on screen. Differs from FlxObject
's implementation
in that it takes the actual graphic into account, not just the hitbox or bounding box or whatever.
Parameters:
Camera | Specify which game camera you want. If |
---|
Returns:
Whether the object is on screen or not.
isSimpleRender(?camera:FlxCamera):Bool
Returns the result of isSimpleRenderBlit()
if FlxG.renderBlit
is
true
, or false
if FlxG.renderTile
is true
.
isSimpleRenderBlit(?camera:FlxCamera):Bool
Determines the function used for rendering in blitting:
copyPixels()
for simple sprites, draw()
for complex ones.
Sprites are considered simple when they have an angle
of 0
, a scale
of 1
,
don't use blend
and pixelPerfectRender
is true
.
Parameters:
camera | If a camera is passed its |
---|
loadGraphic(graphic:FlxGraphicAsset, animated:Bool = false, frameWidth:Int = 0, frameHeight:Int = 0, unique:Bool = false, ?key:String):FlxSprite
Load an image from an embedded graphic file.
HaxeFlixel's graphic caching system keeps track of loaded image data.
When you load an identical copy of a previously used image, by default
HaxeFlixel copies the previous reference onto the pixels
field instead
of creating another copy of the image data, to save memory.
NOTE: This method updates hitbox size and frame size.
Parameters:
graphic | The image you want to use. |
---|---|
animated | Whether the |
frameWidth | Specify the width of your sprite (helps figure out what to do with non-square sprites or sprite sheets). |
frameHeight | Specify the height of your sprite (helps figure out what to do with non-square sprites or sprite sheets). |
unique | Whether the graphic should be a unique instance in the graphics cache.
Set this to |
key | Set this parameter if you're loading |
Returns:
This FlxSprite
instance (nice for chaining stuff together, if you're into that).
loadGraphicFromSprite(Sprite:FlxSprite):FlxSprite
loadRotatedFrame(Frame:FlxFrame, Rotations:Int = 16, AntiAliasing:Bool = false, AutoBuffer:Bool = false):FlxSprite
Helper method which allows using FlxFrame
as graphic source for sprite's loadRotatedGraphic()
method.
Parameters:
frame | Frame to load into this sprite. |
---|---|
rotations | The number of rotation frames the final sprite should have.
For small sprites this can be quite a large number ( |
antiAliasing | Whether to use high quality rotations when creating the graphic. Default is |
autoBuffer | Whether to automatically increase the image size to accommodate rotated corners. Will create frames that are 150% larger on each axis than the original frame or graphic. |
Returns:
this FlxSprite with loaded rotated graphic in it.
loadRotatedGraphic(Graphic:FlxGraphicAsset, Rotations:Int = 16, Frame:Int = -1, AntiAliasing:Bool = false, AutoBuffer:Bool = false, ?Key:String):FlxSprite
Create a pre-rotated sprite sheet from a simple sprite. This can make a huge difference in graphical performance on blitting targets!
Parameters:
Graphic | The image you want to rotate and stamp. |
---|---|
Rotations | The number of rotation frames the final sprite should have.
For small sprites this can be quite a large number ( |
Frame | If the |
AntiAliasing | Whether to use high quality rotations when creating the graphic. Default is |
AutoBuffer | Whether to automatically increase the image size to accommodate rotated corners. Will create frames that are 150% larger on each axis than the original frame or graphic. |
Key | Optional, set this parameter if you're loading |
Returns:
This FlxSprite
instance (nice for chaining stuff together, if you're into that).
makeGraphic(Width:Int, Height:Int, Color:FlxColor = FlxColor.WHITE, Unique:Bool = false, ?Key:String):FlxSprite
This function creates a flat colored rectangular image dynamically.
HaxeFlixel's graphic caching system keeps track of loaded image data. When you make an identical copy of a previously used image, by default HaxeFlixel copies the previous reference onto the pixels field instead of creating another copy of the image data, to save memory.
NOTE: This method updates hitbox size and frame size.
Parameters:
Width | The width of the sprite you want to generate. |
---|---|
Height | The height of the sprite you want to generate. |
Color | Specifies the color of the generated block (ARGB format). |
Unique | Whether the graphic should be a unique instance in the graphics cache. Default is |
Key | An optional |
Returns:
This FlxSprite
instance (nice for chaining stuff together, if you're into that).
pixelsOverlapPoint(worldPoint:FlxPoint, alphaTolerance:Int = 0xFF, ?camera:FlxCamera):Bool
Checks to see if a point in 2D world space overlaps this FlxSprite
object's
current displayed pixels. This check is ALWAYS made in screen space, and
factors in scale
, angle
, offset
, origin
, and scrollFactor
.
Parameters:
worldPoint | point in world space you want to check. |
---|---|
alphaTolerance | Used to determine what counts as solid. |
camera | The desired "screen" coordinate space. If |
Returns:
Whether or not the point overlaps this object.
replaceColor(Color:FlxColor, NewColor:FlxColor, FetchPositions:Bool = false):Array<FlxPoint>
Replaces all pixels with specified Color
with NewColor
pixels.
WARNING: very expensive (especially on big graphics) as it iterates over every single pixel.
Parameters:
Color | Color to replace |
---|---|
NewColor | New color |
FetchPositions | Whether we need to store positions of pixels which colors were replaced. |
Returns:
Array
with replaced pixels positions
inlineresetFrame():Void
Helper method just for convenience, so you don't need to type
sprite.frame = sprite.frame;
You may need this method in tile render mode,
when you want sprite to use its original graphic, not the graphic generated from its framePixels
.
setColorTransform(redMultiplier:Float = 1.0, greenMultiplier:Float = 1.0, blueMultiplier:Float = 1.0, alphaMultiplier:Float = 1.0, redOffset:Float = 0.0, greenOffset:Float = 0.0, blueOffset:Float = 0.0, alphaOffset:Float = 0.0):Void
Sets the sprite's color transformation with control over color offsets.
With FlxG.renderTile
, offsets are only supported on OpenFL Next version 3.6.0 or higher.
Parameters:
redMultiplier | The value for the red multiplier, in the range from |
---|---|
greenMultiplier | The value for the green multiplier, in the range from |
blueMultiplier | The value for the blue multiplier, in the range from |
alphaMultiplier | The value for the alpha transparency multiplier, in the range from |
redOffset | The offset value for the red color channel, in the range from |
greenOffset | The offset value for the green color channel, in the range from |
blueOffset | The offset for the blue color channel value, in the range from |
alphaOffset | The offset for alpha transparency channel value, in the range from |
inlinesetFacingFlip(Direction:FlxDirectionFlags, FlipX:Bool, FlipY:Bool):Void
Set how a sprite flips when facing in a particular direction.
Parameters:
Direction | Use constants |
---|---|
FlipX | Whether to flip the sprite on the X axis. |
FlipY | Whether to flip the sprite on the Y axis. |
setFrames(Frames:FlxFramesCollection, saveAnimations:Bool = true):FlxSprite
Sets frames and allows you to save animations in sprite's animation controller
Parameters:
Frames | Frames collection to set for this sprite. |
---|---|
saveAnimations | Whether to save animations in animation controller or not. |
Returns:
This sprite with loaded frames
setGraphicSize(width:Float = 0.0, height:Float = 0.0):Void
Helper function to set the graphic's dimensions by using scale
, allowing you to keep the current aspect ratio
should one of the numbers be <= 0
. It might make sense to call updateHitbox()
afterwards!
Parameters:
width | How wide the graphic should be. If |
---|---|
height | How high the graphic should be. If |
stamp(Brush:FlxSprite, X:Int = 0, Y:Int = 0):Void
Stamps / draws another FlxSprite
onto this FlxSprite
.
This function is NOT intended to replace draw()
!
Parameters:
Brush | The sprite you want to use as a brush or stamp or pen or whatever. |
---|---|
X | The X coordinate of the brush's top left corner on this sprite. |
Y | They Y coordinate of the brush's top left corner on this sprite. |
transformScreenToPixels(screenPoint:FlxPoint, ?camera:FlxCamera, ?result:FlxPoint):FlxPoint
Converts the point from screen coordinates to this sprite's pixel coordinates where (0,0)
is the top left of the graphic.
Factors in scale
, angle
, offset
, origin
, and scrollFactor
.
Parameters:
screenPoint | The screen coordinates |
---|---|
camera | The desired "screen" coordinate space. If |
result | Optional arg for the returning point |
transformWorldToPixels(worldPoint:FlxPoint, ?camera:FlxCamera, ?result:FlxPoint):FlxPoint
Converts the point from world coordinates to this sprite's pixel coordinates where (0,0)
is the top left of the graphic.
Factors in scale
, angle
, offset
, origin
, and scrollFactor
.
Parameters:
worldPoint | The world coordinates. |
---|---|
camera | The camera, used for |
result | Optional arg for the returning point |
transformWorldToPixelsSimple(worldPoint:FlxPoint, ?result:FlxPoint):FlxPoint
Converts the point from world coordinates to this sprite's pixel coordinates where (0,0)
is the top left of the graphic. Same as worldToPixels
but never uses a camera,
therefore scrollFactor
is ignored
Parameters:
worldPoint | The world coordinates. |
---|---|
result | Optional arg for the returning point |
updateFramePixels():BitmapData
Retrieves the BitmapData
of the current FlxFrame
. Updates framePixels
.
updateHitbox():Void
Updates the sprite's hitbox (width
, height
, offset
) according to the current scale
.
Also calls centerOrigin()
.