Actionscript Image with clickable spots - actionscript-3

Can any one help in suggesting a solution for the following:
i have a large image, consider it as a map, i want to put this image in a viewer that is smaller than the image and i have to be able to scroll the image by clicking and dragging it.
and i want to put in this image a clickable spots in a specified x and y coordinated, and be able to click the spots.
when clicking any spot in the image, the image will be changed with a new spots.. and so on..
can you help in suggesting what is the best object to load the image in and be able to do all the mentioned points.
Thanks in advance.

This is easier than you think. You have a few goals to consider:
"i want to put this image in a viewer that is smaller than the image": You dont need anything special to do this. The concept of this is simply that you have a mask overlay where you want the large image visible.
var viewer:Sprite = new Sprite; //200x200
var imageMask:Sprite = new Sprite; //200x200
var imageContainer:Sprite = new Sprite; //400x500
imageContainer.mask = imageMask;
viewer.addChild(imageContainer);
//this will allow you to visibly see only 200x200 of the
//imageContainer at any time
"i have to be able to scroll the image by clicking and dragging it": This is a little more logic as the imageContainer will have to move in the -(negative) direction of the mouse. Add some listeners to check for mouse actions, and drag as required.
var allowDrag:Boolean = false;
imageContainer.addEventListener(MouseEvent.MOUSE_DOWN, onMouseDown);
imageContainer.addEventListener(MouseEvent.MOUSE_UP, onMouseUp);
imageContainer.addEventListener(MouseEvent.MOUSE_MOVE, onMouseMove);
function onMouseDown(e:Event):void{
allowDrag = true;
}
function onMouseUp(e:Event):void{
allowDrag = false;
}
function onMouseMove(e:Event):void{
//return if not dragging
if(!allowDrag) return;
//move the imageContainer in a -(negative) direction of the mouse
//use an index relative to the size of the viewer and imageContainer
var speed:Number = 0.5;
imageContainer.x -= (viewer.width/imageContainer.width)*speed;
imageContainer.y -= (viewer.height/imageContainer.height)*speed;
//clean the positions so the image remains within the viewer
if(imageContainer.x > 0) imageContainer.x = 0;
if(imageContainer.x < -viewer.width) imageContainer.x = -viewer.width;
if(imageContainer.y > 0) imageContainer.y = 0;
if(imageContainer.y < -viewer.height) imageContainer.y = -viewer.height;
}
"i want to put in this image a clickable spots in a specified x and y coordinated, and be able to click the spots": This also requires a little more thinking. In this case what you want to do is create [hotspots] on the image that are clickable, when clicked = do actions.
//USAGE
//define the click area coords
var clickCoords:Rectangle = new Rectangle();
clickCoords.x = 10; //starts at x 10
clickCoords.y = 10; //starts at y 10
clickCoords.width = 100; //100 wide
clickCoords.height = 100; //100 tall
//add the click listener
var clickArea:Sprite = hotSpot(imageContainer,clickCoords);
clickArea.addEventListener(MouseEvent.CLICK, onHotSoptClick);
//hot spot factory
function hotSpot(target:Sprite,coords:Rectangle):Sprite{
//create the hotspot
var hs:Sprite = new Sprite;
hs.graphics.beginFill(0,0);
hs.graphics.drawRect(0,0,coords.width,coords.height);
hs.graphics.endFill();
//add the hotspot to the target
hs.x = coords.x;
hs.y = coords.y;
target.addChild(hs);
}
function onHotSoptClick(e:MouseEvent):void{
//do something
}
IMPORTANT:
You may want to keep a list of hot spots you create so you can do garbage cleanup, and you plan on dynamically generating hotspots per image... then YOU MUST keep an active list of hot spots and remove when not in use.

You can catch the events MouseDown, MouseUp, MouseMove, MouseOut, on your viewing window, this way you can control exactly what do you want to do.
Here is the pseudo-code:
reset()
{
isDown=false;
downPointX=0;
downPointY=0;
distanceX=0;
distanceY=0;
}
onMouseDown()
{
isDown=true;
downPointX=mouseX;
downPointY=mouseY;
}
onMouseUp()
{
if(distanceX+distanceY==0 and isDown)
click(downPointX,downPointY);
reset();
}
onMouseMove()
{
if isDown then
distanceX=mouseX-downPointX;
distanceY=mouseY-downPointY;
drag(distanceX,distanceY);
endif;
}
onMouseOut()
{
reset();
}
drag(distanceX,distanceY)
{
change your map coordinates
}
click(downPointX,downPointY)
{
if(inSpot(downPointX,downPointY)==true)
changeMap();
endif;
}
changeMap()
{
change your maps and spots
}
avoid implementing any event for your spots sprites or you can get unexpected results.
You can check these for more information
http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/display/Sprite.html#eventSummary

Related

AS3 multiple (movieclip buttons) to animate one movieclip

I am developing a desktop application. I am using ActionScript 3 via Adobe Animate CC. I designed the application, animated the GUI, and started coding. The main functions were successfully coded well, but I have added some additional features which are out of the scope of the application's original goals. All of this just to link the application to a website and some other information, which made me totally crazy because I've spent too much time with very simple if statement LOGIC!
Anyway, I created a menu with three MovieClip buttons. These menu button clicks affect one MovieClip that has a white background that moves with each click. I need there to be one background to show the beautiful effect of easeIn and easeOut animation tweens when clicking each button.
About clicked
Gallery clicked
Contact clicked
To make it easy to understand, I recreated the code with a very simple ball and 3 buttons. If you click first button, the ball moves to the right above the 2nd button. Then the first button should be unclickable, unless another button is clicked. If the second button is clicked, then the ball would move to the right above the third button. Then the second button should be unclickable also, unless another button is clicked. The same thing goes for the third button.
Now, if the first button is clicked again, the animation of the white background should not start from the default position when starting up the application!
It should animated back from its current position to the default position... and so on...
I replaced the white background with a ball for simplicity
This is very easy but I lost it with the eventListeners, eventHandlers, and if statements! :/
I also made this table which studies the cases:
I know my coding technique is not smart enough, but that is because I HATE using classes, packages, project folders... etc..
Even if the code runs too long & repeats, It would be better for me for simplicity, as programming is not my day-job!
Please, any help and quick response would be highly appreciated!
Code:
import flash.ui.Mouse;
import flash.events.MouseEvent;
one.addEventListener(MouseEvent.CLICK, moveToSecondPos);
two.addEventListener(MouseEvent.CLICK, moveToThirdPos);
//three.addEventListener(MouseEvent.CLICK, moveToFirstPos);
var buttonState:Boolean;
one.buttonState = 0;
two.buttonState = 0;
//three.buttonState = 0;
function moveToSecondPos(event:MouseEvent){
if(one.buttonState == 0){
theBall.gotoAndPlay("go1");
one.buttonState = 1;
}
else if(two.buttonState == 1){
theBall.gotoAndPlay("backToOne");
// two.buttonState = 0;
// one.buttonState = 1;
}
else{
//disable About Button
one.removeEventListener(MouseEvent.CLICK, moveToSecondPos);
}
}
function moveToThirdPos(event:MouseEvent){
if((two.buttonState == 0)&&(one.buttonState == 0)){
theBall.gotoAndPlay("goProducts");
two.buttonState = 1;
}
else if(one.buttonState == 1){
theBall.gotoAndPlay("go2");
// two.buttonState = 1;
// one.buttonState = 1;
}
else{
two.removeEventListener(MouseEvent.CLICK, moveToThirdPos);
}
}
//function moveToFirstPos(event:MouseEvent){
// if(three.buttonState == 0){
// theBall.gotoAndPlay("go3");
// three.buttonState = 1;
// }
// else{
// three.removeEventListener(MouseEvent.CLICK, moveToFirstPos);
// }
//}
First, you mentioned you wanted to have the
white background should not start from the default position when starting up the application
For that, you'll need a ShareObject or comparable method of saving and loading data.
Secondly, It appears you may be trying to do some of this with Scenes and Timeline' frames. I highly encourage you not to pursue that.
Below is a solution to the problems you mentioned. Notice that without your project, I had to recreate the scene. You can copy & paste the solution into a new scene and it will compile.
To prevent buttons from being clicked, you can remove the event listener by calling myButton.removeEventListener("click"). Alternatively, you can simply stop the object from responding to mouse events by setting its mouseEnabled property to false.
To animate the box smoothly, you can use the built-in Tween class. Alternatively, I'd direct you Greensock's TweenLite.
Because you appeared to want a series of labels to appear depending on the button clicked, I created an array which stores data specific to each button (btns:Array). By using an organized structure, it's easier to write re-useable code which doesn't depend on explicit functions. Note that there's only one btnListener() function which works for all of your buttons.
Solution
import flash.display.Sprite;
import flash.events.Event;
import flash.text.TextField;
import fl.motion.Color;
import fl.transitions.*;
import fl.transitions.easing.*;
// the list of buttons we want, along with the descriptions for each
var btns:Object = [
{
"label":"About",
"desc":"Learn more about us",
"btn":null
},
{
"label":"Gallery",
"desc":"See our photos",
"btn":null
},
{
"label":"Contact",
"desc":"Write, call, or message",
"btn":null
}
];
var nav:Sprite; // our navigation bar of buttons
var whiteBox:Sprite; // the "ball" with the content text
// where we save the coordinates of the whiteBox between loads
var settings:Object = SharedObject.getLocal("foo");
init();
function init():void {
// Create our navigation of three buttons
// our container for buttons
nav = new Sprite();
// reference to the last button
var last:Sprite = null;
// loop through the list of buttons
for each (var entry:Object in btns) {
// For each button, create a new button
var btn:Sprite = createButton(entry.label);
entry.btn = btn;
nav.addChild(btn);
// If there was a previous button, place this beside it.
if (last != null) {
btn.x = last.x + last.width + 1;
}
last = btn;
}
// Place the nav onscreen
addChild(nav);
nav.x = stage.stageWidth/2 - nav.width/2;
nav.y = stage.stageHeight - nav.height*2;
// Create the whitebox
whiteBox = new Sprite();
whiteBox.graphics.beginFill(0xFAFAFA);
whiteBox.graphics.drawRect(0, 0, 150, 50);
whiteBox.graphics.endFill();
var txt:TextField = new TextField();
txt.name = "txt";
txt.width = 150;
whiteBox.addChild(txt);
nav.addChild(whiteBox);
// Load the settings from the last run of the program.
if (settings.data.hasOwnProperty("x")) {
whiteBox.x = settings.data.x;
whiteBox.y = settings.data.y;
}
}
function createButton(label:String):Sprite {
// Creates a simple button
// Create the label
var txt:TextField = new TextField();
txt.text = label;
// Create the background
var btn:Sprite = new Sprite();
btn.graphics.beginFill(0xA1A1A1);
btn.graphics.drawRect(0, 0, txt.width + 60, txt.height + 30);
btn.graphics.endFill();
btn.addChild(txt);
btn.name = label;
txt.x = 30;
txt.y = 15;
// Hookup events
btn.addEventListener("mouseOver", btnListener);
btn.addEventListener("mouseOut", btnListener);
btn.addEventListener("click", btnListener);
return btn;
}
function btnListener(e:Event):void {
var btn:Sprite = e.currentTarget as Sprite;
var c:Color = new Color();
var entry:Object;
// Find our button in the list.
for each (entry in btns) {
if (entry.label == btn.name) {
break;
}
}
switch (e.type) {
case "mouseOver":
if (btn.mouseEnabled) {
c.setTint(0x0096ff, 0.5);
btn.transform.colorTransform = c;
}
break;
case "mouseOut":
if (btn.mouseEnabled) {
c.setTint(0x00, 0);
btn.transform.colorTransform = c;
}
break;
case "click":
// Set the text, and position of our whitebox
whiteBox.getChildAt(0)["text"] = entry.desc;
whiteBox.y = -whiteBox.height;
var tween:Tween = new Tween(whiteBox, "x", Regular.easeOut, whiteBox.x, btn.x, 0.35, true);
tween.addEventListener("motionFinish", saveState);
for each (var v:Object in btns) {
if (v.btn == btn) {
// make our button unclickable
btn.mouseEnabled = false;
c.setTint(0xFFFFFF, 0.5);
btn.transform.colorTransform = c;
} else {
// Make the other buttons clickable;
v.btn.mouseEnabled = true;
c.setTint(0x00, 0);
v.btn.transform.colorTransform = c;
}
}
break;
}
}
function saveState(e:Event):void {
settings.data.x = whiteBox.x;
settings.data.y = whiteBox.y;
settings.flush();
}

Changing text dynamically with drag / drop in Flash CS6 (AS3)

I have some incredibly simple code that works fine in letting me drag a "slider" button horizontally. However, I also want the text that appears above the object to change depending upon what the x-coordinate is of the object I'm dragging.
Here's the simple code:
var rectangle:Rectangle = new Rectangle(31,944,179,0);
Button.addEventListener(MouseEvent.MOUSE_DOWN, fl_ClickToDrag);
function fl_ClickToDrag(event:MouseEvent):void
{
Button.startDrag(false, rectangle);
}
Button.addEventListener(MouseEvent.MOUSE_UP, fl_ReleaseToDrop);
function fl_ReleaseToDrop(event:MouseEvent):void
{
Button.stopDrag();
gotoAndPlay(20);
}
What I'm wanting to do is have the system determine where the "Button" is in terms of its x-coordinate, and if the x-coordinate is higher than, say, 50, for the text above the "Button" to say "50+", and if the x-coordinate is higher than 100 for the text to change to "100+". I'm also not sure if the x-coordinate should be relative to the rectangle or relative to the entire screen.
Any and all help is appreciated.
You can use a boolean var to indicate if your button is dragged and if, then update your text field like this :
var is_dragged:Boolean = false;
var rectangle:Rectangle = new Rectangle(0, 100, stage.stageWidth - button.width, 0);
stage.addEventListener(Event.ENTER_FRAME, _onEnterFrame);
function _onEnterFrame(e:Event):void {
if(is_dragged){
text_field.text = String(Math.round(button.x / 50) * 50) + '+';
}
}
button.addEventListener(MouseEvent.MOUSE_DOWN, button_onPress);
function button_onPress(e:MouseEvent):void {
button.startDrag(false, rectangle);
is_dragged = true;
}
button.addEventListener(MouseEvent.MOUSE_UP, button_onRelease);
function button_onRelease(e:MouseEvent):void {
button.stopDrag();
is_dragged = false;
}
You can see this code working here.
Hope that can help.

Path glow effect in the mouse over event in actionscript 3

I'm building a board game in action script 3 Adobe flash. In that if i mouseover on a particular pawn, it has to show the number of steps which can be moved by that pawn with respect to dice value with path glow effect.
Here in my code path will glow after i move the pawn with respect to dice number.
opawn1.addEventListener(MouseEvent.CLICK, fl_ClickToGoToAndStopAtFrame_3);
function fl_ClickToGoToAndStopAtFrame_3(event: Mouse): void {
var filterarray: Array=new Array();
opawn1.filters=[glow];
var gfilter: GlowFilter=new GlowFilter();
filterarray.push(gfilter);
current_pawn = arrayPawn[0];
checkSize(opawn1);
if (o_move == 0) {
o_move = 1;
convert_to_movieclip(s1);
}
temp = get_number_of_moves(odirectmove, checkorange, 0, current_pawn);
odirectmove = false;
for(var i=0;i<temp+1;i++)
{
s1[i].filters=filterarray;
}
Here I used mouse click event, Its not working if i change it as mouseover.
Please let me know the above code is correct or not.
How to achieve this?
As #otololua said, the type of your fl_ClickToGoToAndStopAtFrame_3 event parameter should be MouseEvent and not Mouse, then you can change MouseEvent.CLICK by MouseEvent.MOUSE_OVER like this :
opawn1.addEventListener(MouseEvent.MOUSE_OVER, opawn1_on_MouseOver);
function opawn1_on_MouseOver(event:MouseEvent): void {
var glow_filter: GlowFilter = new GlowFilter();
var filters_array: Array = [glow_filter];
your_target_object.filters = filters_array
// ...
}
And if you need that effect be visible only when the mouse is over, you can remove it using MouseEvent.MOUSE_OUT like this :
opawn1.addEventListener(MouseEvent.MOUSE_OUT, opawn1_on_MouseOut);
function opawn1_on_MouseOut(event:MouseEvent): void {
your_target_object.filters = null;
// ...
}
Hope that can help you.

AS3 simple horizontal gallery

I have a simple horizontal gallery of 24 pictures.
The idea is to show 3 pictures on the screen from all (24) and the middle one to be shown above as the big one automaticly ( like the scheme ). This means that when some of the arrows is pressed the movement of the images have to be by one. Also they have to be auto looped. So the first one can go in the middle to.
Here is my code so far. ( I didn't put the all 24 thumbnails, here are only 3 thumbnails only for the tests ) I've managed to move the thumbnails and select a big picture. But I need it to be auto selected when comes to the middle.
buttonL1_btn.addEventListener(MouseEvent.CLICK, left);
buttonR1_btn.addEventListener(MouseEvent.CLICK, right);
function left(event:Event):void{
box_mc.x -=50;
}
function right(event:Event):void{
box_mc.x +=50;
}
//imgs
img_3_big.visible = false;
box_mc.img_1.addEventListener(MouseEvent.CLICK, img1_show);
function img1_show(e:MouseEvent):void {
img_3_big.visible = true;
img_3_big.gotoAndStop(3);
}
box_mc.img_2.addEventListener(MouseEvent.CLICK, img2_show);
function img2_show(e:MouseEvent):void {
img_3_big.visible = true;
img_3_big.gotoAndStop(2);
}
box_mc.img_3.addEventListener(MouseEvent.CLICK, img3_show);
function img3_show(e:MouseEvent):void {
img_3_big.visible = true;
img_3_big.gotoAndStop(1);
}
Although a different approach than what you have already done, the way I would do it is by keeping all 24 images outside of the .swf in their own image files and keeping track of the current image index. Something similar to this (untested code):
import flash.display.Bitmap;
import flash.display.Loader;
import flash.events.MouseEvent;
var allImagePaths:Vector.<String> = new Vector.<String>(); // Holds reference to all big images
var allImageThumbPaths:Vector.<String> = new Vector.<String>(); // Holds reference to all thumbnail images
var currentImageIndex:int = 0; // Keeps track of what image is currently selected
// Loaders that would load big image and thumbnails
var loaderMain:Loader;
var loaderThumb_Left:Loader;
var loaderThumb_Middle:Loader;
var loaderThumb_Right:Loader;
SetupGallery(); // initialize gallery
function SetupGallery()
{
// Setup image loaders
loaderMain = new Loader();
loaderThumb_Left = new Loader();
loaderThumb_Middle = new Loader();
loaderThumb_Right = new Loader();
// Add loaders to existing MovieClips on stage.
imageHolderMain_mc.addChild(loaderMain);
imageHolderThumbLeft_mc.addChild(loaderThumb_Left);
imageHolderThumbMiddle_mc.addChild(loaderThumb_Middle);
imageHolderThumbRight_mc.addChild(loaderThumb_Right);
// Load image paths into a vector collection (like an array)
loadImages();
// Setup arrow button listeners
buttonL1_btn.addEventListener(MouseEvent.CLICK, showImageLeft);
buttonR1_btn.addEventListener(MouseEvent.CLICK, showImageRight);
}
function loadImages()
{
// Initialize collection of images for easier looping/displaying
allImagePaths = new Vector.<String>();
allImageThumbPaths = new Vector.<String>();
// Load up all image paths into the image array(vector).
allImagePaths.push("image1.jpg");
allImageThumbPaths.push("image1_thumb.jpg");
// ... image2 - image23 ...
allImagePaths.push("image24.jpg");
allImageThumbPaths.push("image24_thumb.jpg");
// NOTE: Consider loading paths to image files via xml
}
function showImageLeft(evt:MouseEvent)
{
currentImageIndex--;
showCurrentImage();
}
function showImageRight(evt:MouseEvent)
{
currentImageIndex++;
showCurrentImage();
}
// Call this after each arrow click, direction will be determined by currentImageIndex
function showCurrentImage()
{
// Keep current index within bounds, if out of range then "loop back"
if(currentImageIndex < 0) currentImageIndex = allImagePaths.length - 1;
if(currentImageIndex > allImagePaths.length - 1) currentImageIndex = 0;
// Set right and left thumbnail indexes based on current image
// (Assuming my logic is correct of course :)
var indexRight:int = currentImageIndex - 1;
if(indexRight < 0) indexRight = allImagePaths.length - 1; // "Loop back" if needed
var indexLeft:int = currentImageIndex + 1;
if(indexLeft > allImagePaths.length - 1) indexLeft = 0; // "Loop back" if needed
// clear out any existing images
loaderMain.unload();
loaderThumb_Left.unload();
loaderThumb_Middle.unload();
loaderThumb_Right.unload();
// set correct images based on new indexes
loaderMain.load(allImagePaths[currentImageIndex]);
loaderThumb_Left.load(allImageThumbPaths[indexLeft]);
loaderThumb_Middle.load(allImageThumbPaths[currentImageIndex]);
loaderThumb_Right.load(allImageThumbPaths[indexRight]);
}
There may be some additional things you'll have to handle, but that's the general idea.
Going with this approach you will not deal with keyframes, in fact you would want to have only one keyframe where the AS code is located and you would want to remove all images from the .swf file itself.
This approach will:
Allow for "Looping back" of images when at the end or beginning of the gallery.
Make it easier to add or remove images in the future.
Improve initial load time for the end user.

remove contents (graphic line) from MovieClip

I have an image gallery which loads a detail image, then draws a line next to the image on one side based on image dimensions. Clicking on the image returns one back to the main image thumbnail list, then clicking a thumb loads another image into detail holder. Everything works fine with it, except that the lines, rather than disappearing upon detail image unload, accumulate. Is there a way to clear the contents of the lineDrawing MovieClip without removing it from the stage, so that I can draw a new line in it? I've tried removeChild on the MovieClip, but then the lines disappear entirely, same with placing lineDrawing.clear() at the top of the setupDetail function. Here is my (relevant)code so far, any assistance will be greatly appreciated, I am stumped!
var detailImage:Loader = new Loader();
var lineDrawing:MovieClip = new MovieClip();
setupDetail();
function setupDetail():void {
detail.visible = false;
detail.buttonMode = true;
detail.closeMessage.mouseEnabled = false;
detail.addChild(detailImage);
detailImage.contentLoaderInfo.addEventListener(Event.COMPLETE, fullyLoaded);
// make sure detail is above the gallery
addChild(detail);
detail.addEventListener(MouseEvent.CLICK, onCloseDetail, false, 0, true);
}
function fullyLoaded(evt:Event):void {
var imgHeight:int = evt.target.content.height;
var imgWidth:int = evt.target.content.width;
var hOffset:int = imgWidth + 5 + 27;
var vOffset:int = imgHeight + 5;
detail.addChild(lineDrawing);
if(imgWidth == 600) {
lineDrawing.graphics.lineStyle(3,0x9a9345);
lineDrawing.graphics.moveTo(28,vOffset);
lineDrawing.graphics.lineTo(626,vOffset);
}
else if(imgHeight == 600) {
lineDrawing.graphics.lineStyle(3,0x9a9345);
lineDrawing.graphics.moveTo(hOffset, 1);
lineDrawing.graphics.lineTo(hOffset, 599);
}
}
function onCloseDetail(evt:MouseEvent):void {
// only allow it to be closed if it is at least 90% opaque
if (detailImage.alpha>.9){
detailImage.unload();
TweenLite.to(detail,.5, {autoAlpha:0});
detailImage.unload();
detail.visible = false;
}
}
lineDrawing.graphics.clear()