AS 3.0 stop timer - actionscript-3

Hi i need help to stop the timer in a flash game using as 3.0, i need this to pause the game because i move some targets using the getTimer() function, i can make the targets stop their movement when the game is paused but because the getTimer() keeps running when i unpause the game the targets just dissapear from screen (their position changes too fast). is there a way of stopping the timer or a better way of moving my targets as smooth as the getTimer does? her5e is my code:
//animates targets
private function MoveTarget(e:Event) {
if (!MovieClip(parent).pauseGame) {
//get time passed
timePassed = getTimer() - lastTime;
lastTime += timePassed;
}
//move the target
this.x += dx * timePassed/1000;
//check to see if the target is offscreen
switch (targetType) {
case "small":
if ( dx > 0 && this.x > 771 ) { //left->right target
deleteTarget(false);
} else if ( dx < 0 && this.x < -26 ) { //left<-right target
deleteTarget(false);
}
break;
case "medium":
if ( dx > 0 && this.x > 790 ) { //left->right target
deleteTarget(false);
} else if ( dx < 0 && this.x < -40 ) { //left<-right target
deleteTarget(false);
}
break;
case "big":
if ( dx > 0 && this.x > 800 ) { //left->right target
deleteTarget(false);
} else if ( dx < 0 && this.x < -50 ) { //left<-right target
deleteTarget(false);
}
break;
}
}

Here is a simple solution, but I think you should learn what is timestep, it's a critical concept for game programming, see Fix Your Timestep!
if (!MovieClip(parent).pauseGame) {
//get time passed
timePassed = getTimer() - lastTime;
lastTime += timePassed;
}
else
{
lastTime = getTimer();
return;
}

Related

I am trying to make a MovieClip follow another MovieClip until contact. One MovieClip moves by Accelerometer

This is part of my code but still the enemies don't follow the ship. Any idea what can I do? the ship moves by accelerometer and the enemies spawn from -y coming down the screen. Some help would be really appreciated
//Move Enemies towards Player//
var speed = 5;
if( enemies.x < ship.x )
{
if( enemies.x + enemies.speedX > ship.x )
{
enemies.x = ship.x;
}
else
{
enemies.x += enemies.speedX;
}
}
else if( enemies.x > ship.x )
{
if( enemies.x - enemies.speedX < ship.x )
{
enemies.x = ship.x;
}
else
{
enemies.x -= enemies.speedX;
}
}
if( enemies.y < ship.y )
{
if( enemies.y + enemies.speedY > ship.y )
{
enemies.y = ship.y;
}
else
{
enemies.y += enemies.speedY;
}
}
else if( enemies.y > ship.y )
{
if( enemies.y - enemies.speedY < ship.y )
{
enemies.y = ship.y;
}
else
{
enemies.y -= enemies.speedY;
}
}
//move enemies//
if (enemies.length != 0) {
for (var j: int = 0; j < enemies.length; j++) {
enemies[j].y += 5;
}
}
Thanks in advance...
I agree with Organis. Enemies does appear to be an array so to acces their x and y you would need enemies[0].x. To fix this I'd put the x positions in a for loop like you have for the y coordinate.
Alternatively depending on how many enemies you have I would add a class to the enemy. That way an enemy would spawn and know what to do through it's class. I think this would be simpler as it wouldn't require tidying up an array when an enemy gets removed. You could also adapt it so that each enemy has a random value for speed allowing for more dynamic results.
Good luck
Edit:
Okay, thats my bad just realised I wasn't very clear. what I ment is this:
//move enemies//
if (enemies.length != 0) {
for (var j: int = 0; j < enemies.length; j++) {
enemies[j].y += 5;
}
}
Works fine. Every enemy will move 5 once they are referenced. Why don't you copy and paste the rest of your code into this loop but instead of using enemies.x use enemies[j].x.
I do think the class for each individual enemy would be a better solution and I do think you should have a look into it.
Hope that makes more sense and apologises again.

In AS3 how would i add 2 buttons that would enable the player to move on press instead of using the arrow keys?

I got this code off the internet for the game Pong to work on my AS3 document for my assignment. However i'm pretty much a beginner at code and i'm trying to get this game to work on mobile as the assignment needs a game to work on it.
Because it uses arrow keys, i would like to basically just replace them with buttons instead, one for going up and one for going down. I just don't know the type of code that would allow me to do that.
Something like, when button is pressed, player moves up or down depending which button, but im not sure where to replace the code and what to get rid of.
Here's the "Pong" class file:
package {
import flash.display.MovieClip;
import flash.events.KeyboardEvent;
import flash.ui.Keyboard;
import flash.events.Event;
public class Pong extends MovieClip {
//constants
private var pongUp:MovieClip = new PongUp ;
private var pongDown:MovieClip = new PongDown ;
const ballspeed:int = 10;
const playerspeed:int = 7;
const computerspeed:int = 10;
const computerIntelligence:int = 7;//intelligence is 7 out of 10
//global variables
var vx:int = - ballspeed;// x component of velocity of ball (velocity is speed with direction)
var vy:int = ballspeed;// y component of velocity of ball
var v1:int = 0;// initial velocity of player
var v2:int = 0;// initial velocity of computer
var playerScore:int = 0;
var computerScore:int = 0;
var player:MovieClip = new PongPlayer ;
var computer:MovieClip = new PongComputer ;
var ball:MovieClip = new PongBall ;
public function Pong() {
//init();
addEventListener(Event.ADDED_TO_STAGE,init);
}
//this function will add all event listeners
function init(e:Event):void {
stage.addEventListener(KeyboardEvent.KEY_DOWN,KeyDown);
stage.addEventListener(KeyboardEvent.KEY_UP,KeyUp);
stage.addEventListener(Event.ENTER_FRAME,EnterFrame);
addChild(player);
addChild(computer);
addChild(ball);
player.x = 23;
player.y = 300;
computer.x = 637;
computer.y = 311;
ball.x = 308;
ball.y = 328;
addChild(pongUp);
pongUp.x = 25;
pongUp.y = 700;
addChild(pongDown);
pongDown.x = 530;
pongDown.y = 700;
}
// this function resets the game
function reset():void {
player.y = stage.stageHeight / 2;
computer.y = stage.stageHeight / 2;
ball.x = stage.stageWidth / 2;
ball.y = stage.stageHeight / 2;
if (Math.abs(Math.random() * 2) > 1)
{
vx = - ballspeed;
}
else
{
vx = ballspeed;
}
if (Math.abs(Math.random() * 2) > 1)
{
vy = - ballspeed;
}
else
{
vy = ballspeed;
}
}
//pongDown.addEventListener ( MouseEvent.MOUSE_DOWN,moveDown );
//function moveDown ( e:MouseEvent ): void
//{
//}
//this function sets the velocity of player when key is pressed
function KeyDown(event:KeyboardEvent):void {
if (event.keyCode == Keyboard.UP)
{
v1 = - playerspeed;
}
else if (event.keyCode == Keyboard.DOWN)
{
v1 = playerspeed;
}
}
//this function sets the velocity of player to 0 if key is released
function KeyUp(event:KeyboardEvent):void {
if (event.keyCode == Keyboard.UP || event.keyCode == Keyboard.DOWN)
{
v1 = 0;
}
}
//This function is executed when a frame changes
function EnterFrame(event:Event):void {
//variable decleration
var pHalfHeight = player.height / 2;// half height of player(used for collisions)
var pHalfWidth = player.width / 2;// half width of player (used for collisions)
var bHalfHeight = ball.height / 2;// half height of ball(used for collisions)
var bHalfWidth = ball.width / 2;// half width of ball (used for collisions)
//moving the player
player.y += v1;
//limiting the motion of player (it should not move beyond the stageheight)
if (player.y + pHalfHeight > stage.stageHeight)
{
player.y = stage.stageHeight - pHalfHeight;
}
else if (player.y - pHalfHeight < 0)
{
player.y = 0 + pHalfHeight;
}
//moving the ball
ball.x += vx;
ball.y += vy;
//moving the computer automatically
if (Math.abs(Math.random() * 10) < computerIntelligence)
{
var d:int = computer.y - ball.y;
if (Math.abs(d) > pHalfHeight)
{
if ((d > 0))
{
v2 = - computerspeed;
}
else
{
v2 = computerspeed;
}
}
}
computer.y += v2;
//limiting the motion of computer (it should not move beyond the stageheight)
if (computer.y + pHalfHeight > stage.stageHeight)
{
computer.y = stage.stageHeight - pHalfHeight;
}
else if (computer.y - pHalfHeight < 0)
{
computer.y = 0 + pHalfHeight;
}
//collision with horizontal walls
if (ball.y + bHalfHeight >= stage.stageHeight || ball.y - bHalfHeight <= 0)
{
vy *= -1;
}
//collision with player and computer
if (ball.x - bHalfWidth <= player.x + pHalfWidth)
{
if (Math.abs(ball.y - player.y) <= pHalfHeight)
{
vx = ballspeed;
if ((v1 != 0))
{
vy = 2 * v1;
}
}
}
else if (ball.x + bHalfWidth >= computer.x - pHalfWidth)
{
if (Math.abs(ball.y - computer.y) <= pHalfHeight)
{
vx = - ballspeed;
if ((v2 != 0))
{
vy = v2;
}
}
}
//collision with vertical walls & updating scores
if (ball.x + bHalfWidth >= stage.stageWidth)
{
playerScore += 1;
reset();
}
else if (ball.x - bHalfWidth <= 0)
{
computerScore += 1;
reset();
}
//display the score on the textfield
//txtPlayer.text = String(playerScore);
//txtComputer.text = String(computerScore);
}
}
}
For mobile, you'll want to compile using AIR for Android or iOS. You can then replace:
//this function sets the velocity of player when key is pressed
function KeyDown(event:KeyboardEvent):void {
if (event.keyCode == Keyboard.UP)
{
v1 = - playerspeed;
}
else if (event.keyCode == Keyboard.DOWN)
{
v1 = playerspeed;
}
}
//this function sets the velocity of player to 0 if key is released
function KeyUp(event:KeyboardEvent):void {
if (event.keyCode == Keyboard.UP || event.keyCode == Keyboard.DOWN)
{
v1 = 0;
}
}
with:
function KeyDown(event:TouchEvent):void {
if (event.stageY < player.y){
v1 = - playerspeed;
}else if (event.stageY > player.y){
v1 = playerspeed;
}
}
function KeyUp(event:TouchEvent):void {
v1 = 0;
}
Then replace:
//this function will add all event listeners
function init(e:Event):void {
stage.addEventListener(KeyboardEvent.KEY_DOWN,KeyDown);
stage.addEventListener(KeyboardEvent.KEY_UP,KeyUp);
with:
//this function will add all event listeners
function init(e:Event):void {
stage.addEventListener(TouchEvent.TOUCH_BEGIN, KeyDown);
stage.addEventListener(TouchEvent.TOUCH_END, KeyUp);
And make sure to use TouchEvent instead of KeyboardEvent by replacing:
import flash.events.KeyboardEvent;
with:
import flash.events.TouchEvent;
Now when you hold your finger down on the screen, the "player" will move towards that Y location. If your game is using the X axis, just change the Ys to Xs!
Hope this helps!

Platformer game hit test

Ok, so I have an object on the stage that moves on the "world" movieclip. I'm trying to make it so that when you're moving right. If the movieclip inside the moving movieclip("dude") called hitD collides with the walls in world, the dude stops moving forward.
Screen shots if it might help.
General stage dude object selected
http://prntscr.com/5bgjfq the world is everything but the ball
http://prntscr.com/5bgjuh
hitD
If anyone has any way they can modify these collision physics since my current code is sketchy as hell, all suggestions and ideas are welcome.
var started:Boolean;
const NUMLEVELS = 3;
var status:String;
stage.focus = stage;
if (! started)
{// Only ever do this once!
status = "falling";
started = true;
var speedX:Number = 5;
var speedY:Number = 0;
var topSpeedY:Number = 50;
var start_x:Number = dude.x;
var start_y:Number = dude.y;
var keysDown:Object = new Object();
stage.addEventListener(KeyboardEvent.KEY_DOWN, keyPressed);
stage.addEventListener(KeyboardEvent.KEY_UP, keyReleased);
stage.addEventListener( Event.DEACTIVATE, appDeactivate );
dude.addEventListener(Event.ENTER_FRAME, moveDude);
var W:Number = 15;
var snows:Array = new Array();
}
for (var b:int = 0; b < 50; b++)
{
var snow:Snow = new Snow();
snows.push(snow);
addChild(snow);
}
function cleanup()
{
stage.removeEventListener(KeyboardEvent.KEY_DOWN, keyPressed);
stage.removeEventListener(KeyboardEvent.KEY_UP, keyReleased);
stage.removeEventListener( Event.DEACTIVATE, appDeactivate );
dude.removeEventListener(Event.ENTER_FRAME, moveDude);
}
function keyIsDown(key:uint):Boolean
{
return Boolean(key in keysDown);
}
function keyPressed(e:KeyboardEvent):void
{
keysDown[e.keyCode] = true;
}
function keyReleased(e:KeyboardEvent):void
{
delete keysDown[e.keyCode];
}
function appDeactivate( event:Event ):void
{
// Get rid of all keypress info when app loses focus
keysDown=new Object();
}
function moveDude(e:Event):void
{
var obj:Object = e.target; //setting dude as object
// for now, if you get off the top of the screen you win
if (obj.y < 0)
{
cleanup();
nextScene();
return;
}
// if character dies, restart
if (obj.y > stage.stageHeight + 100)
{
gotoAndStop(1);
obj.x = start_x;
obj.y = start_y;
}
if (death!=null)
{
if (obj.hitTestObject(death))
{
trace("Dead");
}
}
if (status=="falling")
{
speedY++;
if (speedY>topSpeedY)
{
speedY = topSpeedY;
}
for (i = 0; i<2*speedY; i++)
{
obj.y++;
if (world.hitTestPoint(obj.x - obj.width / 2,obj.y,true) || world.hitTestPoint(obj.x + obj.width / 2,obj.y,true))
{
status = "ground";
break;
}
}
}
else if (status == "jumping")
{
speedY--;
for (i = 0; i<2*speedY; i++)
{
obj.y--;
if (world.hitTestPoint(obj.x - obj.width / 2,obj.y - obj.height,true) || world.hitTestPoint(obj.x + obj.width / 2,obj.y - obj.height,true))
{
speedY = 0;
break;
}
}
if (speedY==0)
{
status = "falling";
}
}
else if (status == "ground")
{
if (! world.hitTestPoint(obj.x - 8,obj.y,true) && ! world.hitTestPoint(obj.x + 8,obj.y + 4,true))
{
speedY = 0;
status = "falling";
}
if (keyIsDown(Keyboard.UP))
{
status = "jumping";
speedY = 10;
}
}
if (keyIsDown(Keyboard.DOWN)&&status=="ground")
{
dude.gotoAndStop("duck");
}
else
{
if (keyIsDown(Keyboard.SHIFT))
{
speedX = 10;
}
else
{
speedX = 5;
}
if (keyIsDown(Keyboard.LEFT))
{
for (i = 0; i<speedX; i++)
{
obj.x--;
dude.ball.rotation--; //dude.ball is a movieclip similar to dude.hitD, it spins when you move.
if (world.hitTestPoint(obj.x - obj.width / 2 + 4,obj.y - 8,true) || world.hitTestPoint(obj.x - obj.width / 2,obj.y - obj.height + 8,true))
{
dude.ball.rotation++;
obj.x++;
break;
}
}
}
else if (keyIsDown(Keyboard.RIGHT))
{
//dude.gotoAndStop("right");
//obj.scaleX = 1;
for (i = 0; i<speedX; i++)
{
obj.x++;
dude.ball.rotation++;
// The number in obj.y-4 affects the climbing ability
if (status == "ground")
{
//dude.height+= 0.1;
//dude.width += 0.1;
}//so here I'm checking if it hits the lower corner or top right corner or hitD
if (world.hitTestPoint(dude.hitD.x + obj.hitD.width/2 , obj.hitD.y,true) || world.hitTestPoint(obj.hitD.x + obj.hitD.width/2,obj.hitD.y - obj.hitD.height ,true))
//if (world.hitTestObject(obj))
{
dude.ball.rotation--;
obj.x--;
break;
}
}
}
dude.gotoAndStop(1);
}
while (status == "ground" && (world.hitTestPoint(obj.x-8, obj.y-1, true) || world.hitTestPoint(obj.x+8, obj.y-1, true)))
{
obj.y--;
}
const BORDER = 50;
var diff:int;
// Check right border:
diff = obj.x + BORDER - stage.stageWidth;
if (diff>0 && world.x>=stage.stageWidth-world.width)
{
obj.x -= diff;
world.x -= diff;
background1.x -= diff;
if (death != null)
{
death.x -= diff;
}
}
// Check left border:
diff = obj.x - BORDER;
if (diff<0 && world.x<=0)
{
obj.x -= diff;
world.x -= diff;
background1.x -= diff;
if (death != null)
{
death.x -= diff;
}
}
// Check bottom border:
diff = obj.y + BORDER - stage.stageHeight;
if (diff>0)
{
obj.y -= diff;
world.y -= diff;
background1.y -= diff;
if (death != null)
{
death.y -= diff;
}
}
// Check top border:
diff = obj.y - BORDER;
if (diff<0)
{
obj.y -= diff;
world.y -= diff;
background1.y -= diff;
if (death != null)
{
death.y -= diff;
}
}
if (obj.x > stage.stageWidth - 25)
{
if (currentFrame<NUMLEVELS)
{
gotoAndStop(currentFrame+1);
obj.x = 25;
}
else
{
obj.x = stage.stageWidth - 25;
}
}
else if (obj.x<25)
{
if (currentFrame>1)
{
gotoAndStop(currentFrame-1);
obj.x = stage.stageWidth - 25;
}
else
{
obj.x = 25;
}
}
}
Thanks in advance for any help you can provide :)
For player physics, it's more clear approach to make a central ENTER_FRAME handler function that just for calculating the transformations to be applied to player.
You can still get information from out, but you just process the final output there. Else, it could be problematic, especially when things gets more complex and when you want to add some more feature.(e.g. Imagine in the future, you wanted to add fans on the ground that blows air up, and player have to rise when on them. There you have a lot to change, and probably with many problems.
For collision detection, this function will provide you this information: to which direction(s) the player can't go with variables 'UpColl', 'DownColl', 'Right Coll' and 'LeftColl'.
Then you can refer to this information from your main function that applies the transformation to your player. I'll give example to that also below.
function collEveryFrame(event:Event):void
{
// capture player positions
player_x = WORLD.player.x;
player_y = WORLD.player.y;
// the movie clip object where you store your solid objects. Remember, ALL MovieClip objets inside this MovieClip will taken as solid objects in your game, and regardless their shape, their boundingBox will be taken as collison. So they will all be square.
collContainer = WORLD.cW;
// your player's collision object
playerColl = WORLD.player;
// RIGHT SQUARE COLLISION DETECTION
for (var i:int; i < collContainer.numChildren; i++)
{
// Check if any collision object colliding with player
if (playerColl.hitTestObject(collContainer.getChildAt(i)))
{
// One collision detected. Check 'from which side' does the player colliding with the object;
if (collContainer.getChildAt(i).y > playerColl.y + playerColl.height - p1MoveSpeed)
{
playerColl.y = collContainer.getChildAt(i).y - playerColl.height;
DownColl = true;
}
else if (collContainer.getChildAt(i).y + collContainer.getChildAt(i).height < playerColl.y + p1MoveSpeed)
{
playerColl.y = collContainer.getChildAt(i).y + collContainer.getChildAt(i).height;
UpColl = true;
}
else if (collContainer.getChildAt(i).x + collContainer.getChildAt(i).width < playerColl.x + p1MoveSpeed)
{
playerColl.x = + collContainer.getChildAt(i).x + collContainer.getChildAt(i).width;
LeftColl = true;
}
else if (collContainer.getChildAt(i).x > playerColl.x + playerColl.width - p1MoveSpeed)
{
playerColl.x = + collContainer.getChildAt(i).x - playerColl.width;
RightColl = true;
}
}
}
// RIGHT SQUARE COLLISION DETECTION [End]
}
Transformation function;
function playerMovement(event:Event):void
{
// (apply this for all sides)
// if nothing keeps player from going right;
if (! RightColl)
{
// Apply everything currently pushing the player to right
if (keyIsDown(Keyboard.RIGHT))
{
movement_Right = 15;
}else{
movement_Right = 0;
}
// example fictional wind function returns wind speed
windSpeed = getWindSpeed();
player.x += movement_Right + windSpeed + etc + etc;
// say windSpeed is -5 (Wind is coming from right, so pushing the player to left)
// so if user pressing right arrow key, player will move to right 10px for every frame, else 5px to left, etc.
}
}
In this way, everything about physics will be easy to implement.
For example, when calculating the movement to down, add gravity and jump etc.

Error with jump function when putting script on movieclip

I'm having a problem with my jump function for a platformer engine. I've moved all of the hit testing onto the individual platforms in the level, so I don't have to write things out for each individual one. The problem with this is that only the first movieclip added to the stage can be jumped on to. The others just make the player sink through the floor if up is held down (as they should- as he's not meant to be there there's nothing to stop him).
So the problem is that the check for the jump just isn't registering properly on the second block. Here's the code (sorry about the excessive MovieClip(parent) s)
var playerRef:MovieClip = MovieClip(parent).player;
stage.addEventListener(Event.ENTER_FRAME, hitUpdate);
function hitUpdate(e:Event):void {
if (playerRef.hitTestPoint(playerRef.x,this.y - (playerRef.height/2)) && playerRef.x + playerRef.width > this.x && playerRef.x < this.x + this.width && !MovieClip(parent).upDown) {
MovieClip(parent).downMomentum = 0;
playerRef.y = this.y - playerRef.height;
}
if (playerRef.hitTestPoint(playerRef.x,this.y + this.height) && playerRef.x + playerRef.width > this.x && playerRef.x < this.x + this.width) {
MovieClip(parent).downMomentum = 0;
playerRef.y = this.y + this.height + MovieClip(parent).gravity;
}
if (playerRef.hitTestPoint(this.x,playerRef.y) && playerRef.y + playerRef.height > this.y && playerRef.y < this.y + this.height) {
MovieClip(parent).speed = 0;
playerRef.x = this.x - playerRef.width;
}
if (playerRef.hitTestPoint(this.x + this.width,playerRef.y) && playerRef.y + playerRef.height > this.y && playerRef.y < this.y + this.height) {
MovieClip(parent).speed = 0;
playerRef.x = this.x + this.width;
}
if (playerRef.hitTestObject(this)) {
MovieClip(parent).groundTouch = true;
} else {
MovieClip(parent).groundTouch = false;
}
}
And the jump function runs like this:
stage.addEventListener(Event.ENTER_FRAME, updates);
function updates(e:Event):void{
player.y += downMomentum;
if(!groundTouch && downMomentum < downMomCap){
downMomentum += gravity;
}
if(downMomentum > downMomCap){
downMomentum = downMomCap;
}
if(upDown && !jumping && groundTouch){
jumping = true;
jumpTimer.reset();
jumpTimer.start();
}
}
jumpTimer.addEventListener(TimerEvent.TIMER, jumpTick);
function jumpTick(e:TimerEvent):void{
if(downMomentum*-1 < downMomCap){
downMomentum -= jumpProg * jumpIncrement;
}else{
downMomentum = downMomCap * -1;
}
jumpProg -= 1;
}
jumpTimer.addEventListener(TimerEvent.TIMER_COMPLETE, jumpDone);
function jumpDone(e:TimerEvent):void{
jumpTimer.stop();
jumping = false;
jumpProg = 5;
}
I just can't find a solution to this, though I suspect it's something to do with how it checks for the player touching the platform.

Constrain movement of HSlider Thumb by Accelerometer

I'm moving an HSlider thumb via the accelerometer. The following code works fine. The problem, though, is that as I keep tilting the device, xSpeed continues to increment. This means that when I now tilt it the other way, the thumb doesn't move for a while -- since, depending on how long I was holding tilted in that intial direction, xSpeed has been going up and up.
So this works, but with the abovementioned flaw:
private function readAcc(e:AccelerometerEvent):void
{
xSpeed -= e.accelerationX * 4;
myHSlider.dispatchEvent(new FlexEvent("valueCommit"));
myHSlider.value += xSpeed;
}
But what I want to do is to stop incrementing xSpeed once the hSlider.value == either the minimum or the maximum. Sounds simple, but when I put in if statements, they prevent the thumb from moving at all:
private function readA(e:AccelerometerEvent):void
{
if(h.minimum < h.value && h.maximum > h.value)
{
xSpeed -= e.accelerationX * 4;
h.dispatchEvent(new FlexEvent("valueCommit"));
h.value += xSpeed;
var lastSpeed:Number = xSpeed;
}
else if (h.value == h.minimum || h.value == h.maximum)
{
xSpeed = lastSpeed;
h.dispatchEvent(new FlexEvent("valueCommit"));
h.value += xSpeed;
}
}
What should the logic be to make this work?
Thanks.
Perhaps your slider value is exceeding the min or max limits when you add (or subtract) xSpeed. Check for this, and subtract if the value is too high, or add if the value is too low.
// EDIT: Code modified to reflect most recent comment
if(h.minimum < h.value && h.maximum > h.value)
{
xSpeed -= e.accelerationX * 4;
var lastSpeed:Number = xSpeed;
}
else if (h.value <= h.minimum )
{
xSpeed = 2;
}
else if ( h.value >= h.maximum )
{
xSpeed = -2
}
h.value += xSpeed;
h.dispatchEvent(new FlexEvent("valueCommit"));
OK, have figured this out and wanted to share it. The key is not to mess with setting the hslider's h.value. Rather, just set the x of the thumb, and let the value take care of itself. The accelerometer event calls a handler; in that handler create a moveThumb() function which will adjust that x. Then, from within the moveThumb() function, dispatch the valueCommit event so that the hslider will respond.
private var xSpeed:Number;
private function accUpdateHandler(e:AccelerometerEvent):void
{
xSpeed -= e.accelerationX;
moveThumb();
}
private function moveThumb():void
{
var newX:Number = h.thumb.x + xSpeed;
var newY:Number = h.thumb.y + ySpeed;
if (newX < 0)
{
h.thumb.x = 0;
xSpeed = 0;
}
else if (newX > h.width - h.thumb.width)
{
h.thumb.x = h.width - h.thumb.width;
xSpeed = 0;
}
else
{
h.value += xSpeed;
}
h.dispatchEvent(new FlexEvent("valueCommit"));
}