how to check, whether user is dragging the object rightside or leftside in actionscript 3 - actionscript-3

I am creating a flash based application, where user can change a rectangle shapes, width and height using mouse drag. here is a quick prototype image.
let me explain briefly: In the image you can see, i am having a tiny red rectangle, which one now sitting is starting position and user can drag that only 100px to right side. The idea is when, user is dragging that to right, i want to rectangle also expand right side with that, like a flexible box. if he is dragging back then it will return with that.
so, the doubt is: how will check, whether user is dragging right side or left side. so based on that we can update the rectangle width.
Here is the code :
import flash.geom.Rectangle;
import flash.events.MouseEvent;
var horizRect:Rectangle = new Rectangle(scrollPathHoriz.x, scrollPathHoriz.y, 100, 0);
var horizCount:Number;
//event listener for the anchor point.
scrollHoriz.addEventListener(MouseEvent.MOUSE_DOWN, dragScroller);
stage.addEventListener(MouseEvent.MOUSE_UP, dropScroller);
//mouse down and mouse up event handler.
function dragScroller(evt:MouseEvent):void {
horizCount= scrollHoriz.x;
scrollHoriz.startDrag(false, horizRect);
scrollHoriz.addEventListener(MouseEvent.MOUSE_MOVE, calculateHorizPixel);
}
function dropScroller(evt:MouseEvent):void {
scrollHoriz.stopDrag();
scrollHoriz.removeEventListener(MouseEvent.MOUSE_MOVE, calculateHorizPixel);
}
function calculateHorizPixel(evt:MouseEvent):void {
horizCount ++;
trace(horizCount);
}

Since you are already saving the starting x position,
You simply need the difference between starting position & current position :
function calculateHorizPixel(evt:MouseEvent):void {
var dx = scrollHoriz.x - horizCount;
trace(dx);
}
A negative value of dx indicates that scrollHoriz moved left, else right.

Or try this:
import flash.events.MouseEvent;
stage.addEventListener(MouseEvent.MOUSE_MOVE, moveMouse);
function moveMouse(event:MouseEvent):void
{
var dx:Number = mouseX - stage.stageWidth/2;
trace(dx);
}

Related

Moving A MovieClip to Left/Right Using Touch Events with simultaneous touches

I am Developing a game, AS3 Adobe air targeted for both android and ios, in which you have a movie clip in the center, and two buttons ( left and right ) that should move that movie clip. My goal is to make the shift between the left/right as smooth as possible :
- if the player is touching the left button, the movie clips moves left. if he removes he's finger from the left button, and touches immediately the right button, the movie clip won't move, it's until he re-touches the right button , that the movie clips moves right. I have tried to implement multitouch events, but i seem to have something wrong since this is the behavior i'm getting.
- if the player is touching the left button, the movie clips moves left as expected, if he touches the right button, the movie clip stops as expected, but if he removes his finger from the left button while keeping it on the right button, the movie clip still freezes and don't move, it should move then to the right
This is the code i am using :
leftButtonCreated.addEventListener(TouchEvent.TOUCH_BEGIN,mouseDown);
rightButtonCreated.addEventListener(TouchEvent.TOUCH_BEGIN,mouseDown2);
stage.addChild(leftButtonCreated);
stage.addChild(rightButtonCreated);
function mouseDown(e:TouchEvent):void
{
stage.addEventListener(TouchEvent.TOUCH_END,mouseUp1);
//listen for mouse up on the stage, in case the finger/mouse moved off of the button accidentally when they release.;
addEventListener(Event.ENTER_FRAME,myButtonClick);//while the mouse is down, run the tick function once every frame as per the project frame rate
}
function mouseUp1(e:TouchEvent):void
{
removeEventListener(Event.ENTER_FRAME,myButtonClick);//stop running the tick function every frame now that the mouse is up
stage.removeEventListener(TouchEvent.TOUCH_END,mouseUp1);
}
function mouseDown2(e:TouchEvent):void
{
stage.addEventListener(TouchEvent.TOUCH_END,mouseUp2);
//listen for mouse up on the stage, in case the finger/mouse moved off of the button accidentally when they release.;
addEventListener(Event.ENTER_FRAME,stopDragging);//while the mouse is down, run the tick function once every frame as per the project frame rate
}
function mouseUp2(e:TouchEvent):void
{
removeEventListener(Event.ENTER_FRAME,stopDragging);//stop running the tick function every frame now that the mouse is up
stage.removeEventListener(TouchEvent.TOUCH_END,mouseUp2);
}
function stopDragging(ev2:Event):void
{
if (MC.x <= rightButtonCreated.x)
{
MC.x = MC.x + 10;
}
}
function myButtonClick(ev:Event):void
{
if (MC.x > leftButtonCreated.x)
{
MC.x = MC.x - 10;
}
else
{
}
}
The Code was initially set for mouseEvents, so i tried to shift to touch events so i could fix this problem, and the code above is what i got. Thank you for your time.
EDIT:
And, i use the following code :
var leftButtonCreated:leftB= new leftB();
Your current problem is that both mouseUp1 and mouseUp2 are triggered once you release the left button, as they are both attached to stage. But your actual problem is deeper. You should first move the object left and right if corresponding buttons are pressed, and use TouchEvent.touchPointID to track which touch has been released to understand which button was released.
Also a potential caveat: If you touch both left and right button, then swap fingers while retaining both touches, then release the finger that's over the right button - where should your object move, left or right? I say the correct answer is to the right, as the finger released corresponds to the left button.
leftButtonCreated.addEventListener(TouchEvent.TOUCH_BEGIN,touchDown);
rightButtonCreated.addEventListener(TouchEvent.TOUCH_BEGIN,touchDown);
leftButtonCreated.addEventListener(TouchEvent.TOUCH_END,touchUp);
rightButtonCreated.addEventListener(TouchEvent.TOUCH_END,touchUp);
addEventListener(Event.ENTER_FRAME,moveObject);
function touchDown(e:TouchEvent):void {
var button:DisplayObject=e.currentTarget as DisplayObject;
if (!button) return; // can't fail typecast to DisplayObject in this context, but leave for good measure
if (button==leftButtonCreated) {
leftButtonPressed=true;
leftButtonTouchID=e.touchPointID;
return;
}
if (button==rightButtonCreated) {
rightButtonPressed=true;
rightButtonTouchID=e.touchPointID;
return;
}
}
function touchUp(e:TouchEvent):void {
var button:DisplayObject=e.currentTarget as DisplayObject;
if (!button) return;
var ti:int;
if (button==leftButtonCreated) {
ti=leftButtonTouchID;
if (ti==e.touchPointID) {
leftButtonPressed=false;
}
}
if (button==rightButtonCreated) {
ti=rightButtonTouchID;
if (ti==e.touchPointID) {
rightButtonPressed=false;
}
}
}
function moveObject(e:Event):void {
if (leftButtonPressed) MC.x-=10;
if (rightButtonPressed) MC.x+=10;
if (MC.x<leftButtonCreated.x) MC.x=leftButtonCreated.x;
if (MC.x>rightButtonCreated.x) MC.x=rightButtonCreated.x;
}
EDIT: Apparently SimpleButtons don't allow the events to propagate outside to their parents. Okay, this can still be remedied, but you will have to store the required properties in your Main class.
var leftButtonPressed:Boolean=false;
var rightButtonPressed:Boolean=false;
var leftButtonTouchID:int=0;
var rightButtonTouchID:int=0;
The above code has been updated. Please return to using SimpleButtons directly, as you were using with var leftButtonCreated:leftB= new leftB();.

AS3 - How to use pixel/point detection with mouse event instead of object detection

This seems like it should be so easy that I'm embarrassed to ask, but I just can't get it.
I have a large round MovieClip (being used as a button). This MovieClip contains a PNG with a transparent background inserted into the MovieClip.
Due to its size there are large empty registration areas on the 4 corners (the bounding box).
How can I have the mouse register as being over only the circle pixels and not the blank space (of Alpha channel pixels) in the square boundary box?
Simple sample code:
public function simpleSample () : void
{
mc1.buttonMode = true;
mc1.addEventListener(MouseEvent.CLICK, doStuff);
}
public function doStuff (event:MouseEvent) : void
{
mc2.gotoAndStop(2);
}
Here are 3 different ways to accomplish this.
EDIT Since you've later explained that your button is an image, this first option won't work for you
If the shape flag on hitTestPoint works with your button (eg it's a shape), you can use hitTestPoint inside your mouse click handler to figure out if the click is actually over the object:
public function doStuff(event:MouseEvent){
//only continue if hit test point is true,
//the x and y values are global (not relative to the mc your testing as one might suppose)
//the third parameter should be true, so it takes into account the shape of object and not just it's bounds
if(mc1.hitTestPoint(stage.mouseX, stage.mouseY, true)){
mc2.gotoAndStop(2);
}
}
If the above doesn't work because you have bimtap data in your button, then an easy way to accomplish this is to just add a shape mask to the button.
So, either inside your button using FlasPro, mask everything with a circle shape, or, do it via code by doing the following when you first show the button:
var s:Shape = new Shape();
s.graphics.beginFill(0);
s.graphics.drawCircle(mc1.x + (mc1.width * .5), mc1.y + (mc1.height * .5), mc1.width / 2);
addChild(s);
mc1.mask = s;
If using an image as the button, or you want to set a threshold of how transparent to consider a click, then you can check the transparency of the pixel under the mouse:
function doStuff(event:MouseEvent){
//only continue if pixel under the mosue is NOT transparent
//first, you need a bitmap to work with
//if you know for sure the position of your bitmap, you can do something like this:
var bm:Bitmap = mc1.getChildAt(0) as Bitmap;
//annoyingly though, FlashPro makes timeline bitmaps shapes,
//so the above won't work UNLESS you take your bitmap in the FlashPro Library
//and export it for actionscript, giving it a class name, then it will be an actual bitmap on the timeline.
//As an alternative, you could (very CPU expensively) draw the whole button as a bitmap
var bmd:BitmapData = new BitmapData(mc1.width,mc1.height,true,0x00000000);
bmd.draw(mc1);
var bm:Bitmap = new Bitmap(bmd);
//we get the 32bit pixel under the mouse point
var pixel:uint = bm.bitmapData.getPixel32(bm.x + event.localX,bm.y + event.localY);
//then we grab just the Alpha part of that pixel ( >> 24 & 0xFF ).
//if the value is 0, it's totally transparent, if it's 255, it's totally opaque.
//for this example, let's say anything greater than 0 is considered good to be a click
if((pixel >> 24 & 0xFF) > 0){
mc2.gotoAndStop(2);
}
}

swipe gesture is not smooth for frame jumping

I have made an as3 android app where I have used swipe gesture for going next frame and previous frame. but I want when I jump to next or previous frame it swipes smoothly.I have tried to use tween max but it is not working.I have found that tween plugins always work for movie clips.So how can I make the swipe smooth.Can I make it smooth without tween plugins?here is my code....
Multitouch.inputMode = MultitouchInputMode.GESTURE;
stage.addEventListener (TransformGestureEvent.GESTURE_SWIPE, SwipeHandler);
function SwipeHandler(event:TransformGestureEvent):void
{
switch(event.offsetX)
{
// swiped right
case 1:
{
prevFrame();
break;
}
// swiped left
case -1:
{
if(currentFrame == 10)
{
stop();
}
else
{
nextFrame();
break;
}
}
}
}
In order for you to be able to smooth swap you need to have both frames on your screen, which is not the case with genuine Flash frames. Smooth transitions are animated via ENTER_FRAME handlers, with a potential hide of actual frame change process. So, in order to do a smooth transition, you need to move a picture of one frame to the left, and for the other frame to move in from the right instead of plain nextFrame(). Let's say you have a 60fpa stage, and try to smooth transition left. You will need two screen-sized objects, one depicting current frame and one the frame to be displayed, ready to be displayed as a single transition. An example:
var transition:Sprite;
var bitmaps:Array;
var leftSide:Bitmap
var rightSide:Bitmap;
// initialization code, best placed in constructor
leftSide=new Bitmap();
rightSide=new Bitmap();
bitmaps=[];
transition=new Sprite();
transition.addChild(leftSide);
transition.addChild(rightSide);
rightSide.x=stage.stageWidth; //left side and right side should be aside each other
This is the declaration of the needed structures. The plan is to show the transition, giving it two Bitmaps that will be linked to two different BitmapData objects that'll hold pictures of new frame and old frame. We will draw our current frame on current frame's bitmapdata, then take a stored next frame bitmap data and the do transition.
function swipeHandler((event:TransformGestureEvent):void {
var doSwitch:Boolean=false;
var targetFrame:int=currentFrame;
switch(event.offsetX) {
// swiped right
case 1: {
if (currentFrame>2) {
// let's say we're not allowed to swipe right from frame 2
targetframe=currentFrame-1;
doSwitch=true;
}
break;
}
// swiped left
case -1: {
if(currentFrame < 10) {
targetFrame=currentFrame+1;
doSwitch=true;
}
break;
}
}
if (!doSwitch) return;
// prepare transition
if (!bitmaps[targetFrame]) bitmaps[targetFrame]=new BitmapData(stage.stageWidth,stage.stageHeight,false,0xffffff);
// ^ make a new bitmap if there's none for target frame
if (!bitmaps[currentFrame]) bitmaps[currentFrame]=new BitmapData(stage.stageWidth,stage.stageHeight,false,0xffffff);
// the same for source frame
bitmaps[currentFrame].fillRect(bitmaps[currentFrame].rect,0xffffff);
bitmaps[currentFrame].draw(stage); // draw current frame on the bitmap
// with this and stored bitmaps, old frame would remain drawn on the cached bitmap
// and able to be used as a transition image
if (targetFrame>currentFrame) {
leftSide.bitmapData=bitmaps[currentFrame];
rightSide.bitmapData=bitmaps[targetFrame];
transition.x=0;
// here is the place to initialize TweenMax tween to move "transition"
// and don't forget to removeChild(transition) at the end of the tween
} else {
rightSide.bitmapData=bitmaps[currentFrame];
leftSide.bitmapData=bitmaps[targetFrame];
transition.x=-1*stage.stageWidth;
// same here for tweening
}
stage.addChild(transition);
gotoAndStop(targetFrame);
}
This places a prepared transition object on screen above all the underlying items, effectively masking the exact frame switch, done by gotoAndStop() call. This object's x coordinate can be tweened afterwards, and the object should be removed from stage once the tween is ofer.
Hope this helps.

AS3: is it possibile to set the cursor x and y?

is it possibile to set the position of the mouse cursor? This is what I would like to do: when the user presses the mouse button over a movieclip, the movieclip starts dragging and on enterframe the cursor is positioned in the middle of the movieclip (don't tell me about lockcenter because I can't use it this way since my movieclip registration point is set at its top left corner). Basically, I would like to be able to force the cursor to reach the center of the movieclip when the user clicks it. Is this possible?
I don't have proof, but I think that you are not allowed to take control of the cursor like that.
An alternative would be to hide the actual mouse cursor, and add a custom cursor instead that you could positioned relative to the real cursor position, or in the center of your drag target if that would be easier. The problem would be that you have no way of knowing the exact appearance of the user's cursor.
In other words you're looking for this functionality: SetCursorPos.
You cannot control the cursor with Flash. You'll have to solve it otherwise - what about setting your movieclip's registration point to the center?!
I don't think that's possible. The mouse coordinates are read only.
However I would suggest any of these instead :
Hide the mouse using Mouse.hide();.
Make your own pointer in the location of the mouse.
Control this pointer as per your wish.
or
When the mouse button is pressed, move the movieclip itself, if
possible.
Expanding on loxxy's response:
Instead of moving the mouse cursor to the center of the object with lockCenter, you can manually move the object to be centered about the mouse cursor when the MouseEvent.MOUSE_DOWN event is fired on the object (just before you call startDrag on the object)
Here's a simple example:
package {
import flash.display.Sprite;
import flash.events.MouseEvent;
public class Main extends Sprite{
public function Main() {
var drag_object:Sprite = new Sprite()
drag_object.graphics.beginFill(0xFF0000, .5);
drag_object.graphics.drawRect(0, 0, 50, 50);
drag_object.graphics.endFill();
drag_object.addEventListener(MouseEvent.MOUSE_DOWN, onMouseDown);
drag_object.addEventListener(MouseEvent.MOUSE_UP, onMouseUp);
drag_object.x = 200;
drag_object.y = 300;
addChild(drag_object);
}
private function onMouseDown(e:MouseEvent):void {
var obj:Sprite = e.target as Sprite;
obj.x = e.stageX - (obj.width * .5);
obj.y = e.stageY - (obj.height * .5);
obj.startDrag();
}
private function onMouseUp(e:MouseEvent):void {
var obj:Sprite = e.target as Sprite;
obj.stopDrag();
}
}
}

Flash: Stage.FullscreenInteractive -> Difference if class or 1st frame

example 1: 1st frame of my app
var screenBounds = Screen.mainScreen.bounds; //Bounds of current screen
var full:Sprite = new Sprite(); //Sprite Fullscreen
//Enter Fullscreen
function goFullScreen(e:Event = null) {
//myClass.goFullscreen();
full.graphics.clear();
full.graphics.beginFill(0xccff00);
full.graphics.drawRect(0,0,screenBounds.width, screenBounds.height);
full.graphics.endFill();
addChild(full);
this.stage.displayState = StageDisplayState.FULL_SCREEN_INTERACTIVE;
}
example 2: a normal as class package
private var full:Sprite = new Sprite(); //Sprite to show fullscreen
private var screenBounds = Screen.mainScreen.bounds; //Bounds of current screen
public function favoritesFullscreen():void {
full.graphics.clear();
full.graphics.beginFill(0xccff00);
full.graphics.drawRect(0,0,screenBounds.width, screenBounds.height);
full.graphics.endFill();
addChild(full);
this.stage.displayState = StageDisplayState.FULL_SCREEN_INTERACTIVE;
}
So, tell me WHERE IS THE DIFFERENCE?
I'm a macuser, you know, at the top the menubar and in my case the dock is aligned left
It's weird but example 1 does exactly what it should. It creates a fullscreen rectangle across the ENTIRE screen (from 0,0 to the right bottom)
However, example 2 kind of calculates the width of the top-menubar and the dock and starts the fullscreen rectangle a approx 40px from the left edge of the screen (dock) and 20px from the top (menubar)... i don't get why a external class acts different than as on the first frame.
??? thank you for your help!
I'm guessing it has to do with when the Screen.mainScreen.bounds are retrieved. On compile time, flash internally moves all frame code within functions in the DocumentClass and calls them after the stage has completly initialized. So, in the 1st example, you are retrieving the screenBounds after everything is initializated, but in the 2nd example you are doing it much earlier.
I guess waiting for the ADDED_TO_STAGE event would be enough. If it's not, the first ENTER_FRAME event dispatched should definitely work.