Error #2006: The supplied index is out of bounds - indexing

I keep getting
Error #2006: The supplied index is out of bounds.
at flash.display::DisplayObjectContainer/getChildAt()
at Main/onFrame()
This is mostly referring to this part of my code
else if (comp) //if completion is true
{
var animation = char.getChildAt(2); //
if (animation.currentFrame == animation.totalFrames)
{
animation.stop();
addChild(end);
My animation that I am pulling at the second frame also isn't running at all, though I have checked the symbol and the frames within it, and it should work fine. I'm pretty new to code and this is what I have been taught so far.
This is the rest of my code here.
We are supposed to make a basic game where our character walks to a power up and does a power up animation, followed by an end game title.
package
{
import flash.display.MovieClip;
import fl.motion.easing.Back;
import flash.sampler.Sample;
import flash.events.Event;
import flash.events.KeyboardEvent;
import flash.ui.Keyboard;
public class Main extends MovieClip
{
var bg:Background;
var b:Bubbles;
var b2:Bubbles;
var s:Seaweed;
var pressingRight:Boolean = false;
var pressingLeft:Boolean = false;
var comp:Boolean = false;
var speed:int = 10;
var char:Character;
var pu:PowerUp;
var hit:hit1
var end:EndGame;
public function Main()
{
bg = new Background;
addChild(bg);
char = new Character();
addChild(char);
char.x = stage.stageWidth/2;
char.y = 488;
b = new Bubbles();
addChild(b);
b2 = new Bubbles();
addChild(b2);
b2.y = +b2.height;
s = new Seaweed();
addChild(s);
pu = new PowerUp();
addChild(pu);
pu.x = 200;
pu.y = 450;
pu.height = 50;
pu.scaleX = pu.scaleY;
pu.gotoAndStop("SPIN");
hit = new hit1;
addChild(hit);
hit.x = char.x
hit.y = char.y - 50
end = new EndGame();
end.x = stage.stageWidth/2;
end.y = stage.stageHeight/2;
stage.addEventListener(Event.ENTER_FRAME, onFrame);
stage.addEventListener(KeyboardEvent.KEY_DOWN, keyPressed);
stage.addEventListener(KeyboardEvent.KEY_UP, keyReleased);
}//main()
public function onFrame(e:Event)
{
if (!comp)
//Bubble Movement
b.y -= 1;
b2.y -= 1;
if (b.y >= stage.stageHeight)
{
b.y = b2.y + bg.height;
}
else if (b2.y >= stage.stageHeight)
{
b2.y = b.y + b2.height;
}
//Background & Character Movement
if (pressingRight && char.x < stage.stageWidth/2)
{
char.x += speed * 0.4
}
else if (pressingRight == true && (bg.width + bg.x) > stage.stageWidth)
{
bg.x -= speed * 0.4;
s.x -= speed * 0.6;
pu.x -= speed * 0.4;
}
else if (pressingRight == true)
{
char.x += speed * 0.4;
}
if (pressingLeft == true && char.x > stage.stageWidth/2)
{
char.x -= speed * 0.4;
}
else if (pressingLeft == true && bg.x <0)
{
bg.x += speed * 0.4;
s.x += speed * 0.6;
pu.x += speed * 0.4;
}
else if (pressingLeft)
{
char.x -= speed * 0.4;
}
//Boundaries
if (char.x > stage.stageWidth)
{
char.x = stage.stageWidth;
}
else if (char.x < 0)
{
char.x = 0;
}
//Character Looking Directions
if (pressingLeft == true)
{
char.scaleX = -1;
hit.x = char.x
}
if (pressingRight == true)
{
char.scaleX = 1;
hit.x = char.x
}
//Character Movements
if (pressingRight || pressingLeft)
{
char.gotoAndStop("WALK");
}
else if (!pressingRight || !pressingLeft)
{
char.gotoAndStop("IDLE");
}
//Getting the Power up
if (pu.hitTestObject(hit))
{
char.gotoAndStop("POWER");
comp = true;
pu.gotoAndStop("GONE");
}
// !end
else if (comp) //if completion is true
{
var animation = char.getChildAt(2); //
if (animation.currentFrame == animation.totalFrames)
{
animation.stop();
addChild(end);
}
}//Comp
}//onFrame
public function keyPressed(k:KeyboardEvent)
{
if (k.keyCode == Keyboard.RIGHT)
{
pressingRight = true;
}
else if (k.keyCode == Keyboard.LEFT)
{
pressingLeft = true;
}
} // keyPressed()
public function keyReleased(k:KeyboardEvent)
{
if (k.keyCode == Keyboard.RIGHT)
{
pressingRight = false;
}
else if (k.keyCode == Keyboard.LEFT)
{
pressingLeft = false;
}
} // keyReleased()
}//public class()
}//package()

If you're using a language with zero-based indexing (where array indexes start at 0, not 1) Then this could be the problem.
Frame 1 would be at index [0] and frame 2 would be at index [1].
If you have 2 frames for example and try to access the frame at index[2] you are stepping beyond the bounds of your array and this is probably why you are getting that error message.

Related

Ogmo Tilemap not showing in the game

So I am doing the haxe flixel TurnBasedRPG tutorial
I am pretty much a noob so I wont be surprised if this is just a stupid mistake I did.
But when I try to put my ogmo tilemap into the game, it doesnt show
Here is my Playstate.hx file
package;
import flixel.FlxG;
import flixel.FlxState;
import flixel.addons.editors.ogmo.FlxOgmo3Loader.EntityData;
import flixel.addons.editors.ogmo.FlxOgmo3Loader;
import flixel.tile.FlxTilemap;
class PlayState extends FlxState
{
var player:Player;
var map:FlxOgmo3Loader;
var walls:FlxTilemap;
override public function create()
{
map = new FlxOgmo3Loader(AssetPaths.HaxeFlixel_Tutorial__ogmo, AssetPaths.level_1__json);
walls = map.loadTilemap(AssetPaths.tiles__png, "walls");
walls.follow();
walls.setTileProperties(1, NONE);
walls.setTileProperties(2, ANY);
player = new Player();
map.loadEntities(placeEntities, "entities");
add(walls);
add(player);
super.create();
}
function placeEntities(entity:EntityData)
{
if (entity.name == "player")
{
player.setPosition(entity.x, entity.y);
}
}
override public function update(elapsed:Float)
{
super.update(elapsed);
FlxG.collide(player, walls);
}
}
Player.hx:
package;
import flixel.FlxG;
import flixel.FlxSprite;
import flixel.math.FlxPoint;
import flixel.util.FlxColor;
class Player extends FlxSprite
{
static inline var SPEED:Float = 200;
public function new(x:Float = 0, y:Float = 0)
{
super(x, y);
loadGraphic(AssetPaths.player__png, true, 16, 16);
drag.x = drag.y = 1600;
setSize(8, 8);
offset.set(4, 4);
setFacingFlip(LEFT, false, false);
setFacingFlip(RIGHT, true, false);
animation.add("lr", [3, 4, 3, 5], 6, false);
animation.add("u", [6, 7, 6, 8], 6, false);
animation.add("d", [0, 1, 0, 2], 6, false);
}
function updateMovement()
{
var up:Bool = false;
var down:Bool = false;
var left:Bool = false;
var right:Bool = false;
var newAngle:Float = 0;
right = FlxG.keys.anyPressed([RIGHT, D]);
down = FlxG.keys.anyPressed([DOWN, S]);
left = FlxG.keys.anyPressed([LEFT, A]);
up = FlxG.keys.anyPressed([UP, W]);
if (up || down || left || right)
{
if (up && down)
{
up = down = false;
}
if (left && right)
{
left = right = false;
}
if (up)
{
newAngle = -90;
if (left)
newAngle -= 45;
else if (right)
newAngle += 45;
facing = UP;
}
else if (down)
{
newAngle = 90;
if (left)
newAngle += 45;
else if (right)
newAngle -= 45;
facing = DOWN;
}
else if (left)
{
newAngle = 180;
facing = LEFT;
}
else if (right)
{
newAngle = 0;
facing = RIGHT;
}
// determine our velocity based on angle and speed
velocity.set(SPEED, 0);
velocity.rotate(FlxPoint.weak(0, 0), newAngle);
// if the player is moving (velocity is not 0 for either axis), we need to change the animation to match their facing
if ((velocity.x != 0 || velocity.y != 0) && touching == NONE)
{
switch (facing)
{
case LEFT, RIGHT:
animation.play("lr");
case UP:
animation.play("u");
case DOWN:
animation.play("d");
case _:
}
}
}
}
override function update(elapsed:Float)
{
updateMovement();
super.update(elapsed);
}
}
If you want to see any other file please ask me because I have been stuck on this for 3 hours now

How to fix a bug with 'image_xscale' in GameMaker Studio 2?

I'm making a game in GameMaker Studio 2, and I have a problem. When object turns to left or right, he was puching forward. But he has to be in the same position like the first time.
I tried to use this code:
/// #description vaksciojimas
// You can write your code in this editor
key_right = keyboard_check(vk_right);
key_left = keyboard_check(vk_left);
key_jump = keyboard_check_pressed(vk_space);
var move = key_right - key_left;
hsp = move * walksp;
vsp = vsp + grv;
if (place_meeting(x,y+1,obj_wall)) && (key_jump) {
vsp = -8;
}
//horizontaliai susiduria
if (place_meeting(x+hsp,y,obj_wall)) {
while (!place_meeting(x+sign(hsp),y,obj_wall)) {
x = x + sign(hsp);
}
hsp = 0;
}
x = x + hsp;
//vertikaliai susiduria
if (place_meeting(x,y+vsp,obj_wall)) {
while (!place_meeting(x,y+sign(vsp),obj_wall)) {
y = y + sign(vsp);
}
vsp = 0;
}
y = y + vsp;
//animacijos
if (!place_meeting(x,y+1,obj_wall)) {
sprite_index = sprite_jumping_player;
image_speed = 0;
if (sign(vsp) > 0){
image_index = 1;
}
else {
image_index = 0;
}
}
else {
image_speed = 1;
if (hsp == 0) {
sprite_index = sprite_player;
}
else {
sprite_index = sprite_runing_player;
}
}
if (hsp != 0) { // hsp = horizontal speed
image_xscale = sign(hsp);
}
When I do this, I was wathing this tutorial: https://www.youtube.com/watch?v=fCeyiEcWRAs&t=8s
From the looks of it, I think this has to do with the origin of the sprite.
With the origin, you're deciding where the center of the sprite is. At which point it should rotate/turn around ect.
You need to set the origin in the sprite itself (not the sprite editor, just the sprite image), because by default it's set on top-left. Setting it on middle-center is the usual method. The origin point appears as an "+" symbol.

Set map borders to not cross inside the view area

I am trying to translate an old flash animation with animate. On the original flash animation the map image is draggable and zoomable but the map ´s borders always stick to the sides of the stage if you pan it or zoom it all the way.
On my test i grabbed some code that allows panning and zooming but the map crosses the stage boundaries if you pan all the way, in fact you can make the map dissapear of the stage.
I think there should be a way to draw like a secondary outer stage and not let the map image go beyond it.
This is the code I have.
var that = this;
var clickedX;
var clickedY;
var isDragging = false;
var friction = 0.85;
var speedX = 0;
var speedY = 0;
var mapOriginalX = this.map.x;
var mapOriginalY = this.map.y;
var mapNudge = 5;
var minScale = 0.25;
var maxScale = 3;
function onMouseWheel(e)
{
var delta;
if (e == window.event)
delta = -10 / window.event.wheelDeltaY;
else
delta = e.detail / 30;
var zoomFactor = delta;
scaleMap(zoomFactor);
}
function mouseDown(e)
{
clickedX = stage.mouseX;
clickedY = stage.mouseY;
isDragging = true;
console.log(stage.mouseX);
console.log(stage.mouseY);
}
function stageMouseUp(e)
{
isDragging = false;
}
function update(e)
{
if (isDragging)
{
speedX = stage.mouseX - clickedX;
speedY = stage.mouseY - clickedY;
}
speedX *= friction;
speedY *= friction;
// saber el tamaño actual del mapa en este punto.
that.map.x += speedX;
that.map.y += speedY;
console.log(that.map.y);
console.log(that.map.x);
clickedX = stage.mouseX;
clickedY = stage.mouseY;
//
}
function resetMap()
{
that.map.x = mapOriginalX;
that.map.y = mapOriginalY;
that.map.scaleX = that.map.scaleY = 1;
}
function zoomMap(e) //control visual
{
if (e.currentTarget == that.plusButton)
scaleMap(-0.1);
if (e.currentTarget == that.minusButton)
scaleMap(0.1);
}
function moveMap(e) //control visual
{
if (e.currentTarget == that.upButton)
speedY -= mapNudge;
else if (e.currentTarget == that.rightButton)
speedX += mapNudge;
else if (e.currentTarget == that.downButton)
speedY += mapNudge;
else if (e.currentTarget == that.leftButton)
speedX -= mapNudge;
}
function scaleMap(amount)
{
var map = that.map; // we will scale de map so this goes first.
map.scaleX -= amount; // same as map.scaleX = map.scaleX - amount
map.scaleY = map.scaleX;
if (map.scaleX < minScale)
map.scaleX = map.scaleY = minScale;
else if (map.scaleX > maxScale)
map.scaleX = map.scaleY = maxScale;
}
// listeners
this.map.on("mousedown", mouseDown.bind(this));
this.resetButton.on("click", resetMap.bind(this));
this.plusButton.on("click", zoomMap.bind(this));
this.minusButton.on("click", zoomMap.bind(this));
this.upButton.on("click", moveMap.bind(this));
this.rightButton.on("click", moveMap.bind(this));
this.downButton.on("click", moveMap.bind(this));
this.leftButton.on("click", moveMap.bind(this));
stage.on("stagemouseup", stageMouseUp.bind(this));
document.getElementById('canvas').addEventListener('mousewheel', onMouseWheel.bind(this));
document.getElementById('canvas').addEventListener('DOMMouseScroll', onMouseWheel.bind(this));
createjs.Ticker.addEventListener("tick", update.bind(this));
resetMap();
One trick I usually use is to create a "fence" procedure that checks bounds and corrects them. It will take some setup though.
To use this method, first set up these variables based on your own scene. Perhaps this is what you meant by defining a "second stage?"
var stageLeft = 0;
var stageRight = 500;
var stageTop = 0;
var stageBottom = 500;
this.map.setBounds(0,0,1462, 1047); // Set the values to match your map
var mapBounds = this.map.getBounds();
Then, add this procedure, or a variation of it based on how your map coordinates are set.
// procedure to correct the map x/y to fit the stage
function fenceMap() {
var map = that.map;
var ptTopLeft = map.localToGlobal(mapBounds.x,mapBounds.y);
var ptBotRight = map.localToGlobal(mapBounds.width,mapBounds.height);
if ((ptBotRight.x - ptTopLeft.x) > (stageRight-stageLeft)) {
if (ptTopLeft.x > stageLeft) {
map.x -= ptTopLeft.x - stageLeft;
speedX = 0;
} else if (ptBotRight.x < stageRight) {
map.x -= ptBotRight.x - stageRight;
speedX = 0;
}
}
if ((ptBotRight.y - ptTopLeft.y) > (stageBottom-stageTop)) {
if (ptTopLeft.y > stageTop) {
map.y -= ptTopLeft.y - stageTop;
speedY = 0;
} else if (ptBotRight.y < stageBottom) {
map.y -= ptBotRight.y - stageBottom;
speedY = 0;
}
}
}
Then, just add to the end of your update(), zoomMap(), moveMap(), and scaleMap() functions:
fenceMap();

I Made a maze in AS3 and the maze wont go to my win screen when the player hits the exit

I made A Maze and Action script 3.0 and everything works except when the player touches the exit box (a movie clip called exit) the maze wont go to my win screen.
If someone could help me that'd be great because this is a final project for school
here's my code
var rightArrow:Boolean = false;
var leftArrow:Boolean = false;
var upArrow:Boolean = false;
var downArrow:Boolean = false;
var speed:int = 5;
stage.addEventListener(KeyboardEvent.KEY_DOWN, stage_onKeyDown);
stage.addEventListener(KeyboardEvent.KEY_UP, stage_onKeyUp);
stage.addEventListener(Event.ENTER_FRAME, stage_onEnterFrame);
function stage_onKeyDown(event:KeyboardEvent):void {
if(event.keyCode == Keyboard.RIGHT) rightArrow = true;
if(event.keyCode == Keyboard.LEFT) leftArrow = true;
if(event.keyCode == Keyboard.UP) upArrow = true;
if(event.keyCode == Keyboard.DOWN) downArrow = true;
}
function stage_onKeyUp(event:KeyboardEvent):void {
if(event.keyCode == Keyboard.RIGHT) rightArrow = false;
if(event.keyCode == Keyboard.LEFT) leftArrow = false;
if(event.keyCode == Keyboard.UP) upArrow = false;
if(event.keyCode == Keyboard.DOWN) downArrow = false;
}
function stage_onEnterFrame(event:Event):void {
var rect:Rectangle = player.getBounds(this);
var i:int = 0;
var xBump:int = 0;
var yBump:int = 0;
if(rightArrow) {
xBump = speed;
for(i = 0; i < speed; i++) {
if(maze.hitTestPoint(rect.right + i, player.y, true)) {
xBump = i - 1;
break;
}
}
}
if(leftArrow) {
xBump = -speed;
for(i = 0; i < speed; i++) {
if(maze.hitTestPoint(rect.left - i, player.y, true)) {
xBump = -i + 1;
break;
}
}
}
if(upArrow) {
yBump = -speed;
for(i = 0; i < speed; i++) {
if(maze.hitTestPoint(player.x, rect.top - i, true)) {
yBump = -i + 1;
break;
}
}
}
if(downArrow) {
yBump = speed;
for(i = 0; i < speed; i++) {
if(maze.hitTestPoint(player.x, rect.bottom + i, true)) {
yBump = i - 1;
break;
}
}
}
player.x += xBump;
player.y += yBump;
}
if(player.hitTestObject(exit)) {
gotoAndStop("win");
}
stop();
Your test:
if(player.hitTestObject(exit)) {
gotoAndStop("win");
}
appears to be outside the function stage_onEnterFrame and is thus only executed once. Make sure the closing brace of the function:
player.x += xBump;
player.y += yBump;
} // this one
Comes after the test, like so:
}
player.x += xBump;
player.y += yBump;
if(player.hitTestObject(exit)) {
gotoAndStop("win");
}
} // closing function here, NOT above

Label Printing using iTextSharp

I have a logic to export avery label pdf. The logic exports the pdf with labels properly but when i print that pdf, the page size measurements (Page properties) that i pass isn't matching with the printed page.
Page Properties
Width="48.5" Height="25.4" HorizontalGapWidth="0" VerticalGapHeight="0" PageMarginTop="21" PageMarginBottom="21" PageMarginLeft="8" PageMarginRight="8" PageSize="A4" LabelsPerRow="4" LabelRowsPerPage="10"
The above property values are converted equivalent to point values first before applied.
Convert to point
private float mmToPoint(double mm)
{
return (float)((mm / 25.4) * 72);
}
Logic
public Stream SecLabelType(LabelProp _label)
{
List<LabelModelClass> Model = new List<LabelModelClass>();
Model = RetModel(_label);
bool IncludeLabelBorders = false;
FontFactory.RegisterDirectories();
Rectangle pageSize;
switch (_label.PageSize)
{
case "A4":
pageSize = iTextSharp.text.PageSize.A4;
break;
default:
pageSize = iTextSharp.text.PageSize.A4;
break;
}
var doc = new Document(pageSize,
_label.PageMarginLeft,
_label.PageMarginRight,
_label.PageMarginTop,
_label.PageMarginBottom);
var output = new MemoryStream();
var writer = PdfWriter.GetInstance(doc, output);
writer.CloseStream = false;
doc.Open();
var numOfCols = _label.LabelsPerRow + (_label.LabelsPerRow - 1);
var tbl = new PdfPTable(numOfCols);
var colWidths = new List<float>();
for (int i = 1; i <= numOfCols; i++)
{
if (i % 2 > 0)
{
colWidths.Add(_label.Width);
}
else
{
colWidths.Add(_label.HorizontalGapWidth);
}
}
var w = iTextSharp.text.PageSize.A4.Width - (doc.LeftMargin + doc.RightMargin);
var h = iTextSharp.text.PageSize.A4.Height - (doc.TopMargin + doc.BottomMargin);
var size = new iTextSharp.text.Rectangle(w, h);
tbl.SetWidthPercentage(colWidths.ToArray(), size);
//var val = System.IO.File.ReadLines("C:\\Users\\lenovo\\Desktop\\test stock\\testing3.txt").ToArray();
//var ItemNoArr = Model.Select(ds => ds.ItemNo).ToArray();
//string Header = Model.Select(ds => ds.Header).FirstOrDefault();
int cnt = 0;
bool b = false;
int iAddRows = 1;
for (int iRow = 0; iRow < ((Model.Count() / _label.LabelsPerRow) + iAddRows); iRow++)
{
var rowCells = new List<PdfPCell>();
for (int iCol = 1; iCol <= numOfCols; iCol++)
{
if (Model.Count() > cnt)
{
if (iCol % 2 > 0)
{
var cellContent = new Phrase();
if (((iRow + 1) >= _label.StartRow && (iCol) >= (_label.StartColumn + (_label.StartColumn - 1))) || b)
{
b = true;
try
{
var StrArr = _label.SpineLblFormat.Split('|');
foreach (var x in StrArr)
{
string Value = "";
if (x.Contains(","))
{
var StrCommaArr = x.Split(',');
foreach (var y in StrCommaArr)
{
if (y != "")
{
Value = ChunckText(cnt, Model, y, Value);
}
}
if (Value != null && Value.Replace(" ", "") != "")
{
cellContent.Add(new Paragraph(Value));
cellContent.Add(new Paragraph("\n"));
}
}
else
{
Value = ChunckText(cnt, Model, x, Value);
if (Value != null && Value.Replace(" ", "") != "")
{
cellContent.Add(new Paragraph(Value));
cellContent.Add(new Paragraph("\n"));
}
}
}
}
catch (Exception e)
{
var fontHeader1 = FontFactory.GetFont("Verdana", BaseFont.CP1250, true, 6, 0);
cellContent.Add(new Chunk("NA", fontHeader1));
}
cnt += 1;
}
else
iAddRows += 1;
var cell = new PdfPCell(cellContent);
cell.FixedHeight = _label.Height;
cell.HorizontalAlignment = Element.ALIGN_LEFT;
cell.Border = IncludeLabelBorders ? Rectangle.BOX : Rectangle.NO_BORDER;
rowCells.Add(cell);
}
else
{
var gapCell = new PdfPCell();
gapCell.FixedHeight = _label.Height;
gapCell.Border = Rectangle.NO_BORDER;
rowCells.Add(gapCell);
}
}
else
{
var gapCell = new PdfPCell();
gapCell.FixedHeight = _label.Height;
gapCell.Border = Rectangle.NO_BORDER;
rowCells.Add(gapCell);
}
}
tbl.Rows.Add(new PdfPRow(rowCells.ToArray()));
_label.LabelRowsPerPage = _label.LabelRowsPerPage == null ? 0 : _label.LabelRowsPerPage;
if ((iRow + 1) < _label.LabelRowsPerPage && _label.VerticalGapHeight > 0)
{
tbl.Rows.Add(CreateGapRow(numOfCols, _label));
}
}
doc.Add(tbl);
doc.Close();
output.Position = 0;
return output;
}
private PdfPRow CreateGapRow(int numOfCols, LabelProp _label)
{
var cells = new List<PdfPCell>();
for (int i = 0; i < numOfCols; i++)
{
var cell = new PdfPCell();
cell.FixedHeight = _label.VerticalGapHeight;
cell.Border = Rectangle.NO_BORDER;
cells.Add(cell);
}
return new PdfPRow(cells.ToArray());
}
A PDF document may have very accurate measurements, but then those measurements get screwed up because the page is scaled during the printing process. That is a common problem: different printers will use different scaling factors with different results when you print the document using different printers.
How to avoid this?
In the print dialog of Adobe Reader, you can choose how the printer should behave:
By default, the printer will try to "Fit" the content on the page, but as not every printer can physically use the full page size (due to hardware limitations), there's a high chance the printer will scale the page down if you use "Fit".
It's better to choose the option "Actual size". The downside of using this option is that some content may get lost because it's too close to the border of the page in an area that physically can't be reached by the printer, but the advantage is that the measurements will be preserved.
You can set this option programmatically in your document by telling the document it shouldn't scale:
writer.AddViewerPreference(PdfName.PRINTSCALING, PdfName.NONE);
See How to set initial view properties? for more info about viewer preferences.