Let's say I have a 2D level that is build out of 2D blocks. Some of them are boxes.
The boxes look just the same. No difference! How can I "copy" or clone the graphics of one box to another ? The only difference the boxes will have is that sprite.x and sprite.y have different values. I would probably go that way:
public static function drawBox(graphics:Graphics):void
{
graphics.clear();
// draw box
}
drawBox(box1.graphics);
drawBox(box2.graphics);
drawBox(box3.graphics);
No textures will be used, only vector drawing!
Is this a good practice ? Is there another way to achieve the same ?
Update: Sometimes I draw sprites randomly (very hard to redraw them if I need many instances of one sprite and all its attributes).
You can use the function copyFrom.
Something like this:
var s:Sprite = new Sprite();
s.graphics.beginFill(0);
s.graphics.drawRect(0, 0, 100, 100);
s.graphics.endFill();
addChild(s);
var s2:Sprite = new Sprite();
// Copyfrom accepts a `Graphics` object.
s2.graphics.copyFrom(s.graphics);
s2.x = 100;
s2.y = 100;
addChild(s2);
Have a look at the documentation about copyFrom().
If you treat it like an object in your game you should probably rather consider the OOP-approach #Pier suggested.
This comes in a lot of flavors:
You could extend a class from Sprite and draw the box as soon as the box is ADDED_TO_STAGE by its parent.
public class box extends Sprite
{
protected var _color:uint;
protected var _size:int;
public function box(size:int=100, color:uint=0x000000)
{
super();
_size = size;
_color = color;
this.addEventListener(Event.ADDED_TO_STAGE, onAddedToStage);
}
protected function onAddedToStage(event:Event):void
{
this.removeEventListener(Event.ADDED_TO_STAGE, onAddedToStage);
draw();
}
protected function draw():void
{
this.graphics.beginFill(_color);
this.graphics.drawRect(0,0,_size,_size);
this.graphics.endFill();
}
}
This box can be constructed/created by calling:
var b:box = new box();
this.addChild(b);
Or you could let the box contain itself - which could be more feasible if you deal with a lot of Objects. The box would just need a reference to its parent then - and of course it should provide a dispose()-function
public class box
{
private var _parent:Sprite;
protected var s:Sprite;
public function box(parent:Sprite)
{
_parent = parent;
s = new Sprite();
s.graphics.beginFill(0x00000);
s.graphics.drawRect(0,0,100,100);
s.graphics.endFill();
_parent.addChild(s);
}
public function dispose():void
{
_parent.removeChild(s);
}
}
}
In this case you would construct the box as follows - it requires a reference to a Sprite (or any extension of) that has already been added to the stage:
var b:box = new box(this);
In both cases you could dynamically change attributes and make the object more versatile:
public function set size(val:int):void
{
_size = val;
draw();
}
public function set color(val:uint):void
{
_color = val;
draw();
}
Related
I have a gun child inside of a movieclip called "player" and "player" is inside another movieclip called "level one".
So inside the gun class, the code spawns a bullet. Which has to spawn in the parent's parent. So the bullet can shoot into the level.
private function fire(m: MouseEvent)
{
//when bullet fired
var b = new Bullet;
MovieClip(MovieClip(parent).parent).addChild(b);
}
However, the bullet never appears in the parent's parent. What could be the issue here?
UPDATED CODE:
In gun class:
function fire(e:MouseEvent):void
{
dispatchEvent(new Event('fire!', true));
}
In player class:
protected function fire(e: Event)
{
var b: Bullet = new Bullet();
// bullet must be in same position and angle as player.gun
b.rotation = player.gun.rotation;
b.x = player.gun.x; + player.gun.width * Math.cos(player.gun.rotation / 180 * Math.PI);
b.y = player.gun.y + player.gun.width * Math.sin(player.gun.rotation / 180 * Math.PI);
addChild(b);
}
You missed to strong typing the variable and add parentheses
Try
var b:Bullet = new Bullet();
Why don't you keep a reference to the parent.parent?
var b:Bullet = new Bullet(parent)
...
public function Bullet(spawnTarget:MovieClip)
{
_spawnTarget = spawnTarget;
}
private function fire(m: MouseEvent)
{
//when bullet fired
var b = new Bullet;
_spawnTarget.addChild(b);
}
Using parent.parent is risky because you'd always need to make sure that the gun class is instantiated in a child of the game class. Also, you can't create guns in any other position in the hierarchy which can be a problem if your game grows bigger.
You can solve this with listeners (as the comments state, and this is an example of passing a game reference. Each instance receives a reference to game, so each instance can call public function on game:
Game.as
myPlayer = new Player(this);
public function addBulletToWorld(){
}
Player.as
public function Player(game){
myGun = new Gun(game);
}
Gun.as
public function Gun(game){
game.addBulletToWorld();
}
If you absolutely insist on using the parent.parent thing, just set a break point at that line and see what parent.parent actually is, then adjust as needed to match your actual structure. But aside from the fact that this is just bad practice, it's going to limit you to where you can't use this Class anywhere but at that one depth.
I'd recommend just generating a custom event when you want to fire the bullet, and letting the grandparent handle it.
In Gun:
function fire(e:MoudeEvent):void {
dispatchEvent(new Event('fire!', true));//setting it true lets it bubble up to the parent
}
In Game
protected var bullets:Vector. = new Vector();
public function Game() {
addEventListener('fire!', fire);
}
//note I worked with Flex too long to use private methods very often
protected function fire(e:Event) {
var bullet:Bullet = new Bullet();
bullet.x = MoveClip(e.target).x);
bullet.y = MoveClip(e.target).y);
addChild(bullet);
bullets.push(bullet);//I assume you're going to want to move this or something, so we need to store it to manage it
}
Okay, so I've recently been trying to get my head properly around OOP in AS3. Right now I have a really simple scenario where I've got a class, Paddle, which draws a rectangle. In my document class I create two instances of the Paddle class, paddle1 and paddle2.
I've also created a property for my Paddle class which I want to change the colour of the rectangle that it draws. I want to be able to adjust this property from the main class. I know I could do this by passing in attributes when instantiating the class but it seems like a property would be a better way, and now I want to know if this is the right way of thinking or not.
main class:
package
{
import flash.display.Sprite;
import flash.events.Event;
public class Engine extends Sprite
{
private var paddle1:Paddle = new Paddle();
private var paddle2:Paddle = new Paddle();
public function Engine()
{
paddle1.x = 30;
paddle1.color = 0xFF00FF;
stage.addChild(paddle1);
paddle2.x = stage.stageWidth - 45;
paddle2.color = 0xFF0000;
stage.addChild(paddle2);
}
}
}
Paddle class:
package
{
import flash.display.MovieClip;
import flash.display.Shape;
import flash.display.Graphics;
import flash.events.Event;
public class Paddle extends MovieClip
{
public var color:uint = 0xFFFFFF;
public function Paddle()
{
var child:Shape = new Shape();
child.graphics.beginFill(color);
child.graphics.drawRect(0, 260, 15, 80);
child.graphics.endFill();
addChild(child);
}
}
}
If changing the properties in this way is not the best way of doing things then of course say so. Otherwise, what am I doing wrong that it doesn't work? Seems like it's something to do with the order (by the time the main class changes the colour attribute, it's already created the rectangle and it's too late to change it?)
Thanks :D
EDIT: realised it might help to say what happens when I execute this code. Basically changing the color attribute from the Engine class doesn't change the colour of the rectangle and they both just stay white (FFFFFF)
The issue you're having is that when you do:
new Paddle();
Your constructor code is run. What this means is that the Rectangle has already been drawn with the color defined at the top of the class. You're then changing the color property after this, which as you can see has no effect.
I suggest you make a draw() function for your Paddle. It could accept a color and be used to draw the Rectangle. It might look like this:
public class Paddle extends MovieClip
{
private var _child:Shape;
public function Paddle()
{
_child = new Shape();
addChild(_child);
}
public function draw(color:uint):void
{
_child.graphics.clear();
_child.graphics.beginFill(color);
_child.graphics.drawRect(0, 260, 15, 80);
_child.graphics.endFill();
}
}
This way provides an advantage which is that you can modify the arguments of draw() to accept dimensions for your Rectangle or other elements that will affect the visuals. This will be cleaner and faster than having to add more properties to the class itself if you decide you want to do this.
You're then able to do this:
var paddle1:Paddle = new Paddle();
var paddle2:Paddle = new Paddle();
paddle1.draw(0xFF00FF);
paddle2.draw(0xFF0000);
What you might do is to allow the constructor to assign a color in addition to creating a setter for the color, having both calls subsequently drawing the paddle (which, by the way, could also be a simple flash.display.Shape):
Paddle.as:
package
{
//Imports
import flash.display.Sprite;
//Class
public class Paddle extends Sprite
{
//Constants
private static const DEFAULT_COLOR:uint = 0xFF0000;
//Properties
private var mColor:uint;
//Constructor
public function Paddle(color:uint = DEFAULT_COLOR)
{
mColor = color;
draw();
}
//Draw
private function draw():void
{
graphics.clear();
graphics.beginFill(mColor);
graphics.drawRect(0, 0, 15, 80);
graphics.endFill();
}
//Set Color
public function set color(value:uint):void
{
mColor = value;
draw();
}
//Get Color
public function get color():uint
{
return mColor;
}
}
}
so now you can create and position as many Paddle instances as you want, each having their own color setter:
Red Instance:
var paddleRed:Paddle = new Paddle();
paddleRed.y = 10;
addChild(paddleRed);
Green Instance:
var paddleGreen:Paddle = new Paddle(0x00FF00);
paddleGreen.y = 126;
addChild(paddleGreen);
Blue Instance:
var paddleBlue:Paddle = new Paddle();
paddleBlue.color = 0x00FF00;
paddleBlue.y = 260;
addChild(paddleBlue);
Why not do both? :D
public class Paddle extends MovieClip
{
private var color:uint;
private var rec:Shape;
public function Paddle(newColor:uint = 0xFFFFFF) // default color
{
color = newColor;
rec = new Shape();
drawShape();
addChild(rec);
}
public function drawShape()
{
child.graphics.clear();
child.graphics.beginFill(color);
child.graphics.drawRect(0, 260, 15, 80);
child.graphics.endFill();
}
public function setColor(newColor:uint)
{
color = newColor;
drawShape();
}
}
I need to add a MovieClip to stage, the limitation being that it should only be added to an empty area on the stage. The stage itself either contains complex shapes or is manipulable by the user i.e. he can drag/move objects to change the empty area. The hitTest and hitTestObject methods need DisplayObject already available on the stage. What is the right way to go - the only solution I can imagine is having added my object on the stage and then repeatedly doing hit tests?
[Imagine it to something like adding sprites in a video game - they must spawn in empty regions; if they pop out from inside of each other, then it'll look really odd.]
Well, when you create a new class, just turn it off with a variable and set the visibility to false, then loop until there is no hitTest.
A silly example:
public class someClass extends Sprite
{
private var objectsOnStage:Array;
public function someClass(objectsArray:Array) {
objectsOnStage = objectsArray;
visible = false;
addEventListener(Event.ADDED_TO_STAGE, init);
}
private function init(e:Event){
removeEventListener(Event.ADDED_TO_STAGE, init);
addEventListener(Event.ENTER_FRAME, SEARCH);
}
private function SEARCH(e:Event) {
var doesHit:Boolean = false;
x = Math.round(Math.random() * (550 - 0)) + 0;
y = Math.round(Math.random() * (400 - 0)) + 0;
for (var i:int = 0; i < objectsOnStage; i++) {
if (doesHit) break;
if (this.hitTestObject(objectsOnStage[i])) {
doesHit = true;
}
}
if (doesHit) return;
placedInit();
}
private function placedInit() {
visible = true;
removeEventListener(Event.ENTER_FRAME, SEARCH);
//now init the stuff you want.
}
}
You just check if bounding boxes of both clips overlaps. Like this:
import flash.geom.Rectangle;
import flash.display.MovieClip;
// create simple movie clips that has a rectangle shape inside
var sym1 : MovieClip = new Sym1();
var sym2 : MovieClip = new Sym2();
// get a rectanle of both clipt
var boundingBox1 : Rectangle = sym1.getBounds(this);
var boundingBox2 : Rectangle = sym2.getBounds(this);
// check if bounding boxes of both movie clips overlaps
// so it works like hitTestObject() method
trace( boundingBox1.intersects( boundingBox2) )
I know this post is super old, but in case it helps anybody --
If you need to do a hit test on a movieclip that isn't on the stage. A workaround is to rasterize it to a bitmap first.
var bitmapData:BitmapData = new BitmapData(mc.width, mc.height, true, 0x0000000);
bitmapData.draw(mc);
if (bitmapData.getPixel32(x, y) > 0) {
// Hit true.
}
i created my own Button which simply extends from Sprite.
Its able to show 3 different text fading in and out using a timer.
In my draw function i first draw a rectangle with the Sprites graphics object representing the background of the button.
I added a function to set the button width. This property is used to draw the rectangle. I know that the sprites's size is updated after the rectangle drawing. But for some reason the sprite's width is always more than what i have set via my "setButtonWidth" function.
Now i have a simple sprite acting as a button having a graphics.drawRectangle part drawing a simple rect. with lets say 500px width. But when i trace the width of that button it is always about 10% more. Where are these 10% coming from?
I read about calling validateNow(). But this is only for Labels, or Checkboxes. For some reason i cannot access the library for Label. This must work somehow with TextFields. But how?
// this function is part of MyButtonClass.as file
function drawButton()
{
this.graphics.clear();
this.graphics.beginFill( currentBackColor);
this.graphics.drawRoundRect(0, 0, int(this.buttonWidth)+20, 30, 10, 10);
this.graphics.endFill();
}
// this code is in main action code frame
// the buttonWidth is set this way
stage.addEventListener( Event.RESIZE, updateBtn);
function updateBtn( event:Event)
{
// access the container in which the buttons are in like ...
for( var i = 0; i < buttonContainer.numChildren; i++) {
var btn = buttonContainer.getChildAt( i) as MyButtonClass;
// MyButtonClass is the class which extends from Sprite drawing my button
// and using buttonWidth to draw the backgrounds width.
btn.setButtonWidth( (stage.stageWidth / 2) - 20);
// i set half of stageWidth because i have two columns with a list of buttons
// after setButtonWidth is called in MyButtonClass, the draw function is called
// which does the graphics stuff above.
}
}
this.buttonWidth is set to 500. There is nothing special done on that sprite. No children to be added, only this drawing stuff. But this sets the sprite's width to 550 or something.
Define Button like this
package {
import flash.display.Sprite;
public class Button extends Sprite {
private var _buttonWith: int = 0;
private var _buttonHeight: int = 0;
public function Button() {
// constructor code
}
public function set buttonWidth(w: int): void {
_buttonWith = w;
updateButton();
}
public function get buttonWidth(): int {
return _buttonWith;
}
public function set buttonHeight(h: int): void {
_buttonHeight = h;
updateButton();
}
public function get buttonHeight(): int {
return _buttonHeight;
}
protected function updateButton() {
graphics.clear();
graphics.beginFill(0xff00ff);
graphics.drawRoundRect(0, 0, buttonWidth, buttonHeight, 10, 10);
graphics.endFill();
}
}
}
And create instance like this
var button:Button = new Button();
addChild(button);
button.buttonWidth = 100;
button.buttonHeight = 30;
Okay by deleting correctly I mean am I actually getting rid of the instance or is it just not being drawn anymore? I should mention that I'm trying to delete the instance from within its own class, that is it deletes itself. It 'works' in that the square it draws no longer appears on the screen but again I'm not sure if it's really gone or just not being drawn. Anyway here's the class:
package
{
import flash.display.*;
import flash.events.*;
public class OBJECT_bullet_1 extends Sprite
{
public var X:int = 0; public var Y:int = 0;
public var Y_SPEED:int = 5;
public var DEPTH:int = 9;
public var CONTAINER:Sprite = new Sprite();
public function CREATE(CONTAINER:Sprite,X:int,Y:int):void
{
this.CONTAINER = CONTAINER;
CONTAINER.stage.addEventListener(Event.ENTER_FRAME,STEP);
this.X = X; this.Y = Y;
DRAW();
}
public function STEP(event:Event):void
{
this.graphics.clear();
Y -= Y_SPEED;
if (Y < 20) {Y = 300; CONTAINER.removeChild(this); CONTAINER.stage.removeEventListener(Event.ENTER_FRAME,STEP); CONTAINER.(delete this); CONTAINER = null; return;}
DRAW();
}
public function DRAW():void
{
this.graphics.beginFill(0xCCCC00,1);
this.graphics.drawRect(X - 2,Y - 2,4,4);
this.graphics.endFill();
CONTAINER.addChild(this);
}
}
}
The part I'm concerned about is in the STEP function when it checks to see if Y < 20. You'll notice that it does several things afterwords. Am I deleting it correctly? If so is there anything I am doing to delete it that I don't need to?
Yes to both questions. To ensure an object is deleted, all you have to do is remove all references to it. The child reference and event callback are the only ones the above code is aware of, and you have taken care to remove them both. Nullifying your own container reference is unnecessary, as is whatever you think CONTAINER.(delete this) does.
There are some other significant problems with your supplied code. I made some improvements and heavily commented all changes to explain why I made them.
// You should avoid using the default package. Using the default package
// can make it difficult later on if you start having naming conflicts.
package com.stackoverflow.example {
import flash.display.Sprite;
import flash.events.Event;
import flash.geom.Point;
import flash.utils.getTimer;
// Class names are spelled in CamelCase by convention. Also, note
// that "Object" has a special meaning in AS3 so you should avoid
// using it to refer to anything else. I used here "Entity" instead.
public class EntityBullet1 extends Sprite {
// ALLCAPS when used are reserved for static const names.
// A good use of static consts is to store "magic numbers".
public static const DEFAULT_COLOR:uint = 0xCCCC00;
public static const DEFAULT_SPEED_X:Number = 0;
public static const DEFAULT_SPEED_Y:Number = -100;
public static const DEFAULT_SIZE:Number = 4;
// I'm calculating the time between frames for smoother movement.
public var lastTime:int;
public var color:uint = DEFAULT_COLOR;
public var size:int = DEFAULT_SIZE;
// Instead of separate x and y vars, you can use the Point class.
public var pos:Point;
public var speed:Point;
// Instead of a "create" method do all creation inside the constructor!
public function EntityBullet1(x:Number = 0, y:Number = 0) {
pos = new Point(x, y);
speed = new Point(DEFAULT_SPEED_X, DEFAULT_SPEED_Y);
// You don't need the parent container to access the ENTER_FRAME
// event. Every DisplayObject has its own. Much simpler.
addEventListener(Event.ENTER_FRAME, firstStep);
}
public function draw():void {
// Keep all drawing inside the draw function. Previously,
// clear() was being called inside the step method.
graphics.clear();
graphics.beginFill(color);
graphics.drawRect(pos.x - size/2, pos.y - size/2, size, size);
graphics.endFill();
}
// On the first frame, the field "lastTime" is still uninitialized.
// This method initializes it to the current time and hands off
// future events to the proper step() method.
public function firstStep(event:Event):void {
removeEventListener(Event.ENTER_FRAME, firstStep);
addEventListener(Event.ENTER_FRAME, step);
lastTime = getTimer();
step(event);
}
public function step(event:Event):void {
// To move at a fixed rate regardless of how fast the framerate is,
// you need to calculate the time delta.
var cur:int = getTimer();
var delta:Number = (cur - lastTime) / 1000.0;
lastTime = cur;
// Position equals velocity times time.
pos.x += speed.x * delta;
pos.y += speed.y * delta;
draw();
// Note that all DisplayObjects already have references to their
// parent containers called "parent"!
if (pos.y < 20) {
if (parent != null) parent.removeChild(this);
removeEventListener(Event.ENTER_FRAME, step);
}
}
}
}