Only detecting collision with the visible part of a transparent image (AS3) - actionscript-3

I have a transparent image and a square. I'm wanting to detect when the square collides with the image. However, because the image is transparent it would still detect it colliding with the transparent pixels. So, after some reading I've attempted using BitmapData, which I haven't used before. And so, it isn't working. To be honest I didn't expect the bellow code to work. I just wrote to give you an idea of what I wanted to do and how I wanted to it.
Here's my code:
package
{
import flash.display.Bitmap;
import flash.display.BitmapData;
import flash.display.Sprite;
import flash.events.Event;
/**
* Testing Transparency
* #author Craig Jackson
*/
public class Main extends Sprite
{
public var square:Sprite;
[Embed(source="../lib/TestTransparency.png")]
public var TestTrans:Class;
public var testTransBitmapData:BitmapData = new BitmapData(300, 30, true, 0);
public var testTransBitmap:Bitmap = new TestTrans();
public function Main():void
{
if (stage) init();
else addEventListener(Event.ADDED_TO_STAGE, init);
}
private function init(e:Event = null):void
{
removeEventListener(Event.ADDED_TO_STAGE, init);
startUp();
}
public function startUp():void
{
square = new Sprite();
square.graphics.beginFill(0x666666);
square.graphics.drawRect(0, 0, 50, 50);
square.graphics.endFill();
addChild(square);
testTransBitmapData.draw(testTransBitmap);
addChild(testTransBitmap);
addEventListener(Event.ENTER_FRAME, enterFrame);
}
public function enterFrame(e:Event):void
{
square.x = mouseX;
square.y = mouseY;
if (square.hitTestObject(testTransBitmap))
{
trace("Touching");
}
}
}
Anyone know how I can make the it detect only when the square collides with visible part of the image?
Massive thanks in advance.

Unless you have a personal reason for wanting to implement this yourself, I'd recommend using Corey O'Neil's collision detection kit:
https://code.google.com/p/collisiondetectionkit/

Related

Unable to addChild on MouseCoordinations

What i am trying to do is, to place a new tower each time on MouseX and MouseY. but it seems it isn't working Any Idea guys?
or if you can create a tileMap array and add new child of PrototypeTower each time when we click on the Tower (on x=50, y=400) to select and place wherever we want. When i click the the box at x=50, y=400, the startDrag() doesn't work.
Main.as
package
{
import flash.display.Sprite;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.ui.Mouse;
public class Main extends Sprite
{
private var pTower:PrototypeTower = new PrototypeTower;
private var zTower:PrototypeTower = new PrototypeTower;
private var fTower:PrototypeTower = new PrototypeTower;
public function Main()
{
pTower.x = 50;
pTower.y = 400;
addChild(pTower);
addEventListener(Event.ADDED_TO_STAGE, onAddedToStage);
}
private function onAddedToStage(e:Event):void
{
removeEventListener(Event.ADDED_TO_STAGE, onAddedToStage);
pTower.addEventListener(MouseEvent.CLICK, onClicked);
}
private function onClicked(e:Event):void
{
removeEventListener(MouseEvent.CLICK, onClicked);
zTower.x = mouseX;
zTower.y = mouseY;
addChild(zTower);
zTower.startDrag();
addEventListener(MouseEvent.CLICK, onPlaced);
}
private function onPlaced(e:Event):void
{
removeEventListener(MouseEvent.CLICK, onPlaced);
zTower.stopDrag();
fTower.x = mouseX
fTower.y = mouseY;
addChild(fTower);
}
}
}
PrototypeTower.as
package
{
import flash.display.MovieClip;
import flash.events.MouseEvent;
import flash.events.Event;
public class PrototypeTower extends MovieClip
{
public function PrototypeTower()
{
this.graphics.beginFill(0x00FF00);
this.graphics.drawRect(this.x, this.y, 20, 20);
this.graphics.endFill();
}
}
}
Thank you, i am totally noob, wondering around from days!
Sorry this is just a schematic for now. I'll try to refine it later if you need. Hopefully this clears some things up for you though
When you click the tower, add a new tower at the x,y of the mouse and do some sort of startDrag(tower) on the new tower you just added. Then when you click on the stage, stop the drag and set the new X,y
edit
You might try getting rid of all your removeEventListener calls
I think your problem is you are removing the event listener that gets added in your main function. Keep in mind that the main function (class constructor) for the document class only gets called once, so you add an event listener for ADDED_TO_STAGE only once, and then you remove it the first time you try to add anything to the stage, and you never put it back. Just don't remove it in the first place.
You are calling zTower.startDrag() before you add it to the stage. Do addChild(zTower) and then zTower.startDrag()

Changing class properties in AS3

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();
}
}

Dragging a movieclip as3

I have a Movieclip which is a child of another movieclip. I use startDrag() and stopDrag() with first (parent) Movieclip but the nested one doesnt move. Why?
relevant code on stage:
var main:rt = new rt(); // rt being a class in my library, which extends MovieClip object.
addChild(main);
stage.addEventListener(MouseEvent.MOUSE_DOWN, stage_mousedownHandler);
stage.addEventListener(MouseEvent.MOUSE_UP, stage_mouseupHandler);
function stage_mousedownHandler(event_object:Event) {
main.startDrag();
}
function stage_mouseupHandler(event_object:Event) {
main.stopDrag();
}
rt's constructor code:
public function rt() {
var bmp_bar:Bitmap;
var br_male:Bar_male; // Bar_male is a Bitmap in my library. (AS Linkage)
bmp_bar = new Bitmap(br_male);
this.addChild(bmp_bar);
}
Made this simple program to test and it works as expected in Flash Develop, there is a main sprite and a child bitmap when I mouse down any where on stage the main sprite is dragged and the child bitmap is moved.
So I am guessing there is something going on in your workflow in flash professional and linkage. Make sure the mouse event handlers are triggered put some breakpoints and debug.
package
{
import flash.display.Bitmap;
import flash.display.BitmapData;
import flash.display.Sprite;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.geom.Rectangle;
public class Test extends Sprite
{
private var sp:Sprite = new Sprite();
public function Test()
{
addEventListener(Event.ADDED_TO_STAGE, onAddedToStage);
}
private function onAddedToStage(e:Event):void
{
removeEventListener(Event.ADDED_TO_STAGE, onAddedToStage);
var bmpData:BitmapData = new BitmapData(100, 100,false,0x000000);
bmpData.fillRect(new Rectangle(0, 0, 100, 100), 0xff0000);
var bmp:Bitmap = new Bitmap(bmpData);
sp.addChild(bmp);
addChild(sp);
stage.addEventListener(MouseEvent.MOUSE_DOWN, onMouseDown);
stage.addEventListener(MouseEvent.MOUSE_UP, onMouseUp);
}
private function onMouseUp(e:MouseEvent):void
{
sp.stopDrag();
}
private function onMouseDown(e:MouseEvent):void
{
sp.startDrag();
}
}
}

Need some help completing a bumptop-ish selection tool

I'm in the midst of creating a Bumptop styled selection tool. Right now I got as far as creating the tool itself (which actually works pretty good) and spreading some random square items on the stage. This is the class that creates the selection tool :
package com.reyco1.medusa.selectiontool
{
import flash.display.Sprite;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.geom.Point;
public class SelectionBase extends Sprite
{
private var points:Array = [];
public function SelectionBase()
{
super();
addEventListener(Event.ADDED_TO_STAGE, initialize);
}
private function initialize(e:Event):void
{
removeEventListener(Event.ADDED_TO_STAGE, initialize);
points.push(new Point(mouseX, mouseY)); stage.addEventListener(MouseEvent.MOUSE_MOVE, handleMouseMove);
}
private function handleMouseMove(e:MouseEvent):void
{
graphics.clear();
graphics.beginFill(0x33CCFF, .5);
graphics.drawCircle(0, 0, 20);
graphics.endFill();
graphics.moveTo(0, 0);
graphics.lineStyle(1.5, 0x33CCFF, .5);
graphics.lineTo(mouseX, mouseY);
points.push(new Point(mouseX, mouseY));
graphics.beginFill(0x33CCFF, .1);
graphics.moveTo(points[0].x, points[0].y);
for (var i:uint = 1; i < points.length; i++)
{
graphics.lineTo(points[i].x, points[i].y);
}
graphics.lineTo(points[0].x, points[0].y);
graphics.endFill();
dispatchEvent(new Event("UPDATE"));
}
public function clear():void
{
stage.removeEventListener(MouseEvent.MOUSE_MOVE, handleMouseMove);
graphics.clear();
}
}
}
And this is the document class that implements it :
package
{
import com.reyco1.medusa.selectiontool.SelectionBase;
import flash.display.Sprite;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.display.StageAlign;
import flash.display.StageQuality;
import flash.display.StageScaleMode;
[SWF(width = '1024', height = '768', backgroundColor = '0x000000')]
public class SelectionToolPrototype extends Sprite
{
private var selectionTool:SelectionBase;
public function SelectionToolPrototype()
{
stage.align = StageAlign.TOP_LEFT;
stage.scaleMode = StageScaleMode.NO_SCALE;
stage.quality = StageQuality.MEDIUM;
stage.addEventListener(MouseEvent.MOUSE_DOWN, handleDown);
stage.addEventListener(MouseEvent.MOUSE_UP, handleUp);
placeShapesRandomly();
}
private function placeShapesRandomly():void
{
for(var a:Number = 0; a<25; a++)
{
var s:Sprite = new Sprite();
s.graphics.beginFill(Math.random() * 0xCCCCCC);
s.graphics.drawRect(0, 0, 50, 50);
s.graphics.endFill();
s.x = Math.floor(Math.random() * 900 - 40) + 40;
s.y = Math.floor(Math.random() * 700 - 40) + 40;
s.rotation = Math.floor(Math.random() * 360 - 40) + 40;
s.buttonMode = true;
addChild(s);
}
}
private function handleUp(e:MouseEvent):void
{
selectionTool.removeEventListener("UPDATE", handleToolUpdate);
removeChild(selectionTool);
selectionTool = null;
}
private function handleDown(e:MouseEvent):void
{
selectionTool = new SelectionBase();
selectionTool.addEventListener("UPDATE", handleToolUpdate);
selectionTool.x = mouseX;
selectionTool.y = mouseY;
addChild(selectionTool);
}
private function handleToolUpdate(e:Event):void
{
// logic to determin if items are within selection goes here
}
}
}
I've tried using collision detection by means of BitmapData and even using collision libraries like CDK but I cant get anything to work. Anybody have an idea what I should use in the handleToolUpdate(e:MouseEvent); ? Thanks!
Update:
I'll break it down. Basically I am trying to create a prototype of the BumpTop Lasso or Selection tool.
I need help in finding out which objects either collide or have a point within the bounds of the drawn lasso.
I have upload what I have so far to my server here : http://labs.reyco1.com/bumptop/SelectionToolPrototype.html. You can see the source by right clicking and selecting "View Source".
Like I said in my earlier post, I tried using Bitmapdata collision testing and even tried using the Collision Detection Kit to no avail. Thanks in advance.
Loop through the display object you are attaching your random sprites to, and using for each, check their value of hitTestObject against your selectionTool instance.
Here are the Adobe docs for hitTestObject():
http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/display/DisplayObject.html#hitTestObject%28%29

Flash CS4 AS3 horizontal movieclip scrolling with mouse move

I'm new to AS3 and have been working on an XML driven navigation system written in AS3.
At present, I've imported the contents of an XML file and plotted it inside a containing MovieClip created at root level dynamically on the stage. This MovieClip is called 'container'.
What I want to accomplish is a smooth, accelerating / decelerating effect which animates the container movieclip along the X axis depending on where the mouse cursor is in relation to the middle of the stage.
My code can be found here: http://pastie.org/521432
Line 87 onwards is the code I'm using right now to make the movieclip scroll left & right.
What I have does work but is clunky but does work - I just want it to be a little more polished and have drawn a blank with Google. Because I want the MovieClip to continue to scroll at the current relative speed even when the mouse stops moving, I used an instance of the Timer class.
Can anyone suggest improvements? Thanks in advance.
You should separate out you calculations and your drawing methods. So have it do all the calculations in an onMouseMove handler, but actually draw the changes in an onEnterFrame handler.
Also I think your algorithm could be much simpler and nobody would notice. I made a quick example of how you might do it. paste this code into an AS3 file called Main.as and make it the document class of a new FLA.
package
{
import flash.display.MovieClip;
import flash.display.Sprite;
import flash.events.Event;
import flash.events.MouseEvent;
public class Main extends Sprite
{
private const boxCount:int = 10;
private const boxWidth:int = 45;
private const boxMargin:int = 5;
private const startPoint:int = 150;
private const boxesWidth:int = boxCount * (boxWidth + boxMargin);
private const endPoint:int = boxesWidth + startPoint;
private const zeroPoint:int = boxesWidth / 2 + startPoint;
private var container:MovieClip;
private var targetX:Number;
private var speed:Number = 0;
public function Main():void
{
if (stage) init();
else addEventListener(Event.ADDED_TO_STAGE, init);
}
private function init(e:Event = null):void
{
removeEventListener(Event.ADDED_TO_STAGE, init);
container = new MovieClip();
addChild(container);
container.x = 150;
container.y = 300;
for (var i:int = 0; i < boxCount; i++)
{
container.graphics.beginFill(Math.random() * 0xFFFFFF);
container.graphics.drawRect(i*(boxWidth+boxMargin), 0, boxWidth, boxWidth);
}
addEventListener(Event.ENTER_FRAME, enterFrameHandler);
stage.addEventListener(MouseEvent.MOUSE_MOVE, mouseMoveHandler);
}
private function mouseMoveHandler(e:MouseEvent):void
{
var distanceFromCenter:int = stage.mouseX - zeroPoint;
speed = distanceFromCenter * -0.01; // Bring number into a good range, and invert it.
}
private function enterFrameHandler(e:Event):void
{
container.x += speed;
}
}
}