Flex 4: Title window goes out of accessible area - apache-flex

I have a strange issue- I use a title window to create a message to the user. The user has the ability to move the title window around the screen so that the main screen is visible.
However if the user were to move the title window way too much, it can actually go outside the browser accessible area- the user has no option but to close the browser and start again. How do we ensure that the title window movement is limited, such that the title bar is always available for control?
I might not have worded this right- pls check the attached image.

I'd listen to the move event of the TitleWindow. If the window is moved out of the visible coordinates of the application, move it back.
If you're only issue is w/ allowing the users to closet the window, then you could add a "Close" button on the bottom of the window in addition to the 'x' at the top.

If you can use a custom component I'd suggest you override the TitleWindow's move() method. I'm using the following code to restrict the window movement:
public class PopUpWindow extends TitleWindow
{
private static const MIN_VISIBLE:int = 50;
public override function move(x:Number, y:Number):void
{
var maxX:Number = stage.stageWidth - MIN_VISIBLE;
var maxY:Number = stage.stageHeight - MIN_VISIBLE;
if (x < 0)
x = 0;
else if (x > maxX)
x = maxX;
if (y < 0)
y = 0;
else if (y > maxY)
y = maxY;
super.move(x, y);
}
}

This function is called on move event of titlewindow:
protected function titlewindow1_moveHandler(event:MoveEvent):void
{
// TODO Auto-generated method stub
var window:UIComponent = event.currentTarget as UIComponent;
var application:UIComponent = FlexGlobals.topLevelApplication as UIComponent;
var bounds:Rectangle = new Rectangle(0, 0, application.width, application.height);
var windowBounds:Rectangle = window.getBounds(application);
var x:Number;
var y:Number;
if (windowBounds.left <= bounds.left)
x = bounds.left;
else if (windowBounds.right >= bounds.right)
x = bounds.right - window.width;
else
x = window.x;
if (windowBounds.top <= bounds.top)
y = bounds.top;
else if (windowBounds.bottom >= bounds.bottom)
y = bounds.bottom - window.height;
else
y = window.y;
window.move(x, y);
}

Related

Unity - Making Camera Lock on To Enemy and stay behind player?

I am attempting to create a Camera that moves with the Player but locks onto an enemy when the player clicks the lock on button. The behaviour is almost working as I want it, the camera locks onto the target. And when the player stand in-front of the target it works fine. However as soon as the player runs past the target, the camera behaves strangely. It still looks at the Enemy, however it does not stay behind the player. Here is the code that dictates the behaviour:
if(MouseLock.MouseLocked && !lockedOn){ // MOUSE CONTROL:
Data.Azimuth += Input.GetAxis("Mouse X") * OrbitSpeed.x;
Data.Zenith += Input.GetAxis("Mouse Y") * OrbitSpeed.y;
} else if(lockedOn) { // LOCKON BEHAVIOUR:
FindClosestEnemy();
}
if (Target != null) {
lookAt += Target.transform.position;
base.Update ();
gameObject.transform.position += lookAt;
if(!lockedOn){
gameObject.transform.LookAt (lookAt);
} else if(enemyTarget != null) {
Vector3 pos1 = Target.transform.position ;
Vector3 pos2 = enemyTarget.transform.position ;
Vector3 dir = (pos2 - pos1).normalized ;
Vector3 perpDir = Vector3.Cross(dir, Vector3.right) ;
Vector3 midPoint = (pos1 + pos2) / 2f;
gameObject.transform.LookAt (midPoint);
}
}
And the Code for Finding the nearest Enemy:
void FindClosestEnemy () {
int numEnemies = 0;
var hitColliders = Physics.OverlapSphere(transform.position, lockOnRange);
foreach (var hit in hitColliders) {
if (!hit || hit.gameObject == this.gameObject || hit.gameObject.tag == this.gameObject.tag){
continue;
}
if(hit.tag != "Enemy") // IF NOT AN ENEMY: DONT LOCK ON
continue;
var relativePoint = Camera.main.transform.InverseTransformPoint(hit.transform.position);
if(relativePoint.z < 0){
continue;
}
numEnemies += 1;
if(enemyTarget == null){
print ("TARGET FOUND");
enemyTarget = hit;
}
}
if(numEnemies < 1){
lockedOn = false;
enemyTarget = null;
}
}
As I said, teh behaviour almost works as expected, however I need the camera to stay behind the player whilst locked on and it must face the enemy/midPoint between the enemy and player. How can this be done? Thank you for your time.
To clarify your intent: you want to lock the position relative to the target (player), whilst setting the camera rotation to look at either the target or a secondary target (enemy)? And your current code performs the rotation correctly but the positioning is buggy?
The easiest way to fix the camera relative to another object is to parent it in the scene. In your case you could add the camera as a child under the Player game object.
If you would rather not do this then look at your positioning code again:
lookAt += Target.transform.position;
base.Update ();
gameObject.transform.position += lookAt;
I don't know where lookAt comes from originally but to me this looks all wrong. Something called lookAt should have nothing to do with position and I doubt you want to += anything in the positioning code given that you want a fixed relative position. Try this instead:
public float followDistance; // class instance variable = distance back from target
public float followHeight; // class instance variable = camera height
...
if (Target != null) {
Vector3 newPos = target.position + (-Target.transform.forward * followDistance);
newPos.y += followHeight;
transform.position = newPos;
}
This should fix the positioning. Set the followDistance and followHeight to whatever you desire. Assuming your rotation code works this should fix the problem.

Unity3D - 2D object rotation based on touch moved (diff between touches)

I´m newbie in Unity. I want rotate my 2D object based on user touch moved (moved finger on the screen). I have this code:
void Update ()
{
if (Input.touches.Length > 0) {
t = Input.GetTouch (0);
if (t.phase == TouchPhase.Moved) {
Vector3 movePos = new Vector3 (t.position.x, t.position.y, 0);
var objectPos = Camera.main.WorldToScreenPoint (transform.position);
var dir = movePos - objectPos;
transform.rotation = Quaternion.Euler (new Vector3 (0f, 0f, Mathf.Atan2 (dir.y, dir.x) * Mathf.Rad2Deg));
}
}
}
This code rotate the object based on user touch but when I touch screen again in another position and do touch move, it will rotate the whole object to the actual touch and then it will do correct object rotation based on touch move.
And I dont´t want rotate the whole object based on touch position but rotate the object only based on touch move. Do you understand me? Can you help me? How should I rewrite my code?
If I understand you, try to use this code below:
private float turnSpeed = 5f;
private Vector2 movement;
void Update()
{
Vector2 currentPosition = transform.position;
if (Input.touchCount > 0)
{
Touch touch = Input.GetTouch(0);
if (touch.phase == TouchPhase.Moved)
{
Vector2 moveTowards = Camera.main.ScreenToWorldPoint(touch.position);
movement = moveTowards - currentPosition;
movement.Normalize();
}
}
float targetAngle = Mathf.Atan2(movement.y, movement.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.Euler(0, 0, targetAngle), turnSpeed * Time.deltaTime);
}
Let me know if is what you want. Also, there is a complete sample here: https://github.com/joaokucera/unity-2d-object-rotation
Look into using deltaPosition instead of position on your touch. That should get you in the right direction.
var movedVector = t.deltaPosition;
Edit:
Here is a possible integration with your existing code. I don't have Unity on this PC so this is entirely untested. The main idea is you are getting a change in the finger position between frames. You then scale that change by move speed, and of course, the change in time between frame renders (delta time).
How the object rotates relative to that information is up to you. I just inserted the logic into your existing code.
float moveSpeed = 2.0f;
void Update ()
{
if (Input.touches.Length > 0) {
t = Input.GetTouch (0);
if (t.phase == TouchPhase.Moved) {
var delta = t.deltaPosition * moveSpeed * Time.deltaTime;
transform.rotation = Quaternion.Euler (new Vector3 (0f, 0f, Mathf.Atan2 (delta .y, delta.x) * Mathf.Rad2Deg));
}
}
}

Flex 4.5 mobile Resize textarea with animation on soft keyboard activate event?

I'm using Flex 4.5.1 with AIR 2.7 (and Flash Builder 4.5.1) to build an app for the Blackberry Playbook.
The app has a large textarea that needs to be resized when the soft keyboard shows up. I am able to hook into the soft keyboard events and do things there.
Now, I want to resize the textarea to fit the remaining part of the screen when the keyboard shows up. I know the current and destination size and want to use a smooth animation to show the textarea resizing. (I can't already set the height and can see the textarea being correctly resized in the keyboard_activating event - but I want to do it through an animation). I've tried using the Animate class, the spark.effects.Move class and none of them seem to work in this case. They seem to run the animation but the screen does not get refreshed!
I don't want to use the built-in resizeAppForKeyboard property on the ViewNavigatorApplication. I have set to 'none' in the app descriptor so that part of it is fine.
Any ideas / thoughts? Is my approach correct at all? How would one go about resizing the textarea using an animation in the keyboard activating event? My code looks like:
In the main view (onCreationComplete event): (txNote is the textarea in question)
txNote.addEventListener(SoftKeyboardEvent.SOFT_KEYBOARD_ACTIVATE, function(e:SoftKeyboardEvent):void {
toggleEditMode(true);
});
txNote.addEventListener(SoftKeyboardEvent.SOFT_KEYBOARD_DEACTIVATE, function(e:SoftKeyboardEvent):void {
toggleEditMode(false);
});
private function toggleEditMode(keyboardActivated:Boolean):void {
trace("toggle edit: " + editMode + ", kb activating: " + keyboardActivated + ", txNote height = " + txNote.height);
editMode = keyboardActivated;
//we handle resize manually, because we want a nice animation happening and we want to resize only the text area - nothing else.
var y:Number = editMode ? -38 : 0;
var height:Number = editMode ? 218 : 455;
txNote.moveAndSize(y, height);
}
The code in txNote.moveAndSize:
public function moveAndSize(newY:Number, newHeight:Number):void {
//parent group uses BasicLayout
//(this.parent as Group).autoLayout = false;
//resizePath.valueFrom = this.height;
//resizePath.valueTo = newHeight;
//movePath.valueFrom = this.y;
//movePath.valueTo = newY;
//resizeEffect.heightFrom = this.height;
//resizeEffect.heightTo = height;
this.top = newY;
moveEffect.xFrom = this.x;
moveEffect.xTo = this.x;
moveEffect.yFrom = this.y;
moveEffect.yTo = newY;
moveEffect.end();
moveEffect.play([ this ]);
//this.move(x, newY);
//animate.play([ this ]);
//this.height = height;
//this.y = y;
//setLayoutBoundsSize(width, height);
//setLayoutBoundsPosition(x, y);
}
The moveEffect / movePath / animate various things I tried are set up in the txNote constructor as follows:
public class NotesArea extends TextArea {
// private var animate:Animate;
// private var movePath:SimpleMotionPath;
// private var resizePath:SimpleMotionPath;
private var moveEffect:Move;
// private var resizeEffect:Resize;
public function NotesArea() {
super();
// animate = new Animate();
// var paths:Vector.<MotionPath> = new Vector.<MotionPath>();
// movePath = new SimpleMotionPath("top");
// resizePath = new SimpleMotionPath("height");
// paths.push(movePath);
//paths.push(resizePath);
// animate.duration = 300;
// animate.motionPaths = paths;
// animate.addEventListener(EffectEvent.EFFECT_UPDATE, function(e:EffectEvent):void {
// trace("y = " + y);
// invalidateDisplayList();
// });
// animate.addEventListener(EffectEvent.EFFECT_END, function(e:EffectEvent):void {
// trace("EFFECT ended: y = " + y);
// });
moveEffect = new Move();
moveEffect.duration = 250;
moveEffect.repeatCount = 1;
moveEffect.addEventListener(EffectEvent.EFFECT_END, function (e:EffectEvent):void {
//(this.parent as Group).autoLayout = true;
trace("move effect ran. y = " + y + ", top = " + top);
});
//this.setStyle("moveEffect", moveEffect);
//
// resizeEffect = new Resize();
// resizeEffect.duration = 250;
// this.setStyle("resizeEffect", resizeEffect);
}
}
yourTextField.addEventListener(SoftKeyboardEvent.SOFT_KEYBOARD_DEACTIVATE, onActivating);
yourTextField.addEventListener(SoftKeyboardEvent.SOFT_KEYBOARD_ACTIVATING, onActivating);
yourTextField.addEventListener(SoftKeyboardEvent.SOFT_KEYBOARD_ACTIVATE, onActivating);
// in the event listener to the textField IE :
private function onActivating(event:SoftKeyboardEvent):void
{
//listen to the event; make your move here.
}

Center window component

I have create a window component but it will randomly position whether I open its window, x and y positions will only offset the elements, not window. How do I position it to the center of the screen?
Flex 4 (AS3):
private function openDoc():void {
if (newWindow != null) newWindow.close();
newWindow = new docwin();
newWindow.width = 500;
newWindow.height = 320;
newWindow.type = "normal";
newWindow.systemChrome = "standard";
newWindow.transparent = false;
newWindow.setStyle("showFlexChrome", true);
newWindow.showStatusBar = false;
newWindow.minimizable = false;
newWindow.maximizable = false;
newWindow.resizable = false;
newWindow.open();
}
Try this:
newWindow.x = Math.ceil((Capabilities.screenResolutionX - newWindow.width) / 2);
newWindow.y = Math.ceil((Capabilities.screenResolutionY - newWindow.height) / 2);
You can use layout property of window like horizontalCentre and verticalCentre use contstraint based layout scheme
You have to position the new window with reference to stageWidth and stageHeight properties.
Assuming the origin of your new window is top left, the new location of the the windows will be:
(Stage.stageWidth - newWindow.width)/2, (Stage.stageHeight - newWindow.height)/2;

AIR: component behaves wrong after switching window

Ok so I have a component, that has a function to remove itself as a popUp in its current Window, and add itself to a newly created Window.
It works, however, if the component has a child like a ComboBox, the drop down still pops up in the old window where it used to be, also scrollbars, and focus seems to behave incorrectly in the new window also.
It seems to me like Flex still thinks the component is a child of the original window, not the new window. I have no idea how to resolve this though.
Here is my code:
private var ownWindow:Window;
private var _inOwnWindow:Boolean;
private var _removedEffect:Move;
private var _openX:Number;
private var _openY:Number;
public function launchInNewWindow(e:Event):void
{
_openX = Application.application.nativeWindow.x + this.x + 5; //keep in same spot add 5 for systemChrom border
_openY = Application.application.nativeWindow.y + this.y + 30;//keep in same spot add 30 for systemChrom title
this.parent.removeChild(this);
ownWindow = new Window();
ownWindow.systemChrome = 'none';
ownWindow.type = NativeWindowType.LIGHTWEIGHT;
ownWindow.transparent = true;
ownWindow.setStyle('showFlexChrome', false);
ownWindow.width = this.width > 750 ? 750 : this.width;
ownWindow.height = this.height > 550 ? 550 : this.height;
edit.enabled = false;
_removedEffect = this.getStyle('removedEffect') as Move;
if(_removedEffect == null)
{
openNewWindow();
}
else
{
// Wait for removed effect to play before adding to new window
_removedEffect.addEventListener(EffectEvent.EFFECT_END,delayOpenInNewWindow);
}
}
private function delayOpenInNewWindow(e:Event = null):void
{
var t:Timer = new Timer(100,1);
t.addEventListener(TimerEvent.TIMER,openNewWindow);
t.start();
}
private function openNewWindow(e:Event = null):void
{
ownWindow.addChild(this);
ownWindow.width += 5; //add to show dropshadow
ownWindow.height += 10; //add to show dropshadow
ownWindow.open();
_inOwnWindow = true;
ownWindow.nativeWindow.x = _openX;
ownWindow.nativeWindow.y = _openY;
}
Any ideas?
Thanks!!
Before I give this a run, have you tried a callLater on the openNewWindow() line?
[ lame fix attempt, i know -- but given that there doesn't seem to be an event that you can listen for in the case that the removedEffect isn't null and it seems like a timer is your only option there, I think it's o.k. to give lame fix attempts :-) ]

Resources