How to smooth 'zoom' and 'pan' of image in as3 - actionscript-3

I am using ActionScript 3 in Adobe Animate to zoom and pan for drawings. Whenever the center button in the control panel is clicked, the image doesn't appear in the center, it appears a bit right below..
Example of how photo inside MovieClip is not centred to the stage.
Also, the pan and zoom are not smooth. The code that I am using is creating a video clip of image and there is a control panel to control the zoom and pan. Please let me know the changes required to make it smooth and workable.
The AS3 code is given below:
import flash.events.MouseEvent;
import flash.events.Event;
var moveSpeed: Number = 5;
var sizeScale: Number = 0.04;
var clickMore: Boolean = false;
var clickLess: Boolean = false;
var clickLeft: Boolean = false;
var clickRight: Boolean = false;
var clickUp: Boolean = false;
var clickDown: Boolean = false;
var clickCenter: Boolean = false;
// --- Click Zoom more:
btMore.addEventListener(MouseEvent.MOUSE_DOWN, moreZoom);
function moreZoom(event: MouseEvent): void {
clickMore = true;
}
btMore.addEventListener(MouseEvent.MOUSE_UP, stopMoreZoom);
function stopMoreZoom(event: MouseEvent): void {
clickMore = false;
}
// --- Click Zoom less:
btLess.addEventListener(MouseEvent.MOUSE_DOWN, lessZoom);
function lessZoom(event: MouseEvent): void {
clickLess = true;
}
btLess.addEventListener(MouseEvent.MOUSE_UP, stopLessZoom);
function stopLessZoom(event: MouseEvent): void {
clickLess = false;
}
// --- Click Move left:
btLeft.addEventListener(MouseEvent.MOUSE_DOWN, leftMove);
function leftMove(event: MouseEvent): void {
clickLeft = true;
}
btLeft.addEventListener(MouseEvent.MOUSE_UP, stopLeftMove);
function stopLeftMove(event: MouseEvent): void {
clickLeft = false;
}
// --- Click Move right:
btRight.addEventListener(MouseEvent.MOUSE_DOWN, rightMove);
function rightMove(event: MouseEvent): void {
clickRight = true;
}
btRight.addEventListener(MouseEvent.MOUSE_UP, stopRightMove);
function stopRightMove(event: MouseEvent): void {
clickRight = false;
}
// --- Click Move up:
btUp.addEventListener(MouseEvent.MOUSE_DOWN, upMove);
function upMove(event: MouseEvent): void {
clickUp = true;
}
btUp.addEventListener(MouseEvent.MOUSE_UP, stopUpMove);
function stopUpMove(event: MouseEvent): void {
clickUp = false;
}
// --- Click Move Down:
btDown.addEventListener(MouseEvent.MOUSE_DOWN, downMove);
function downMove(event: MouseEvent): void {
clickDown = true;
}
btDown.addEventListener(MouseEvent.MOUSE_UP, stopDownMove);
function stopDownMove(event: MouseEvent): void {
clickDown = false;
}
// --- Click Move Center:
btCenter.addEventListener(MouseEvent.MOUSE_DOWN, centerMove);
function centerMove(event: MouseEvent): void {
clickCenter = true;
}
btCenter.addEventListener(MouseEvent.MOUSE_UP, stopCenterMove);
function stopCenterMove(event: MouseEvent): void {
clickCenter = false;
}
// --- Click Zoom Wheel:
stage.addEventListener(MouseEvent.MOUSE_WHEEL, handleMouseWheel);
function handleMouseWheel(event: MouseEvent): void {
if (myMCimg.scaleX >= 1) {
myMCimg.scaleX += (event.delta * sizeScale);
myMCimg.scaleY += (event.delta * sizeScale);
} else {
myMCimg.scaleX = 1;
myMCimg.scaleY = 1;
}
}
// --- Actions:
addEventListener(Event.ENTER_FRAME, enterFrame);
function enterFrame(event: Event): void {
if (clickMore == true) {
myMCimg.scaleX += sizeScale;
myMCimg.scaleY += sizeScale;
}
if ((clickLess == true) && (myMCimg.scaleX >= 1)) {
myMCimg.scaleX -= sizeScale;
myMCimg.scaleY -= sizeScale;
}
if (clickLeft == true) {
myMCimg.x -= moveSpeed;
}
if (clickRight == true) {
myMCimg.x += moveSpeed;
}
if (clickUp == true) {
myMCimg.y -= moveSpeed;
}
if (clickDown == true) {
myMCimg.y += moveSpeed;
}
if (clickCenter == true) {
// --- Centralize:
myMCimg.scaleX = 1;
myMCimg.scaleY = 1;
myMCimg.x = stage.stageWidth / 2;
myMCimg.y = stage.stageHeight / 2;
}
}
// --- Click keys directions keyboard:
stage.addEventListener(KeyboardEvent.KEY_DOWN, pressKeys);
function pressKeys(event: KeyboardEvent): void {
if (event.keyCode == Keyboard.LEFT) {
myMCimg.x -= moveSpeed;
}
if (event.keyCode == Keyboard.RIGHT) {
myMCimg.x += moveSpeed;
}
if (event.keyCode == Keyboard.UP) {
myMCimg.y -= moveSpeed;
}
if (event.keyCode == Keyboard.DOWN) {
myMCimg.y += moveSpeed;
}
if (event.keyCode == Keyboard.ENTER) {
// --- Centralize:
myMCimg.scaleX = 1;
myMCimg.scaleY = 1;
myMCimg.x = stage.stageWidth / 2;
myMCimg.y = stage.stageHeight / 2;
}
// --- Click Drag:
myMCimg.addEventListener(MouseEvent.MOUSE_DOWN, dragMove);
function dragMove(event: MouseEvent): void {
myMCimg.startDrag();
}
myMCimg.addEventListener(MouseEvent.MOUSE_UP, stopDragMove);
function stopDragMove(event: MouseEvent): void {
stopDrag();
}
}

(1) Centralize :
To centralize by width (horizontal), try also subtracting by half-width of picture like:
myMCimg.x = (stage.stageWidth / 2) - (myMCimg.width / 2);
Same logic for centralizing by height (vertical).
(2) Zoom :
As for smooth zoom, I haven't tested your code so not sure what the visual problem "not smooth" means exactly. Maybe it's your output settings? In your Publish Settings (press Ctrl+Shift+F12) does "smoothness" improve if you try those 3 Hardware Acceleration options: None, Direct and GPU?
Finally, I can only suggest you try something like this below as an alternative (maybe it helps) :
To test the code...
Create 2 different colour boxes on stage.
Convert each box to MovieClip (not as Button).
Give each box an instance name (example: zoom_in and zoom_out).
Add/convert image into some MovieClip with instance name pic.
First example will update zoom via mouse roll-over...
zoom_in.addEventListener(MouseEvent.MOUSE_OVER, process_zoom_rollover);
zoom_in.addEventListener(MouseEvent.MOUSE_OUT, process_zoom_rollout);
zoom_out.addEventListener(MouseEvent.MOUSE_OVER, process_zoom_rollover);
zoom_out.addEventListener(MouseEvent.MOUSE_OUT, process_zoom_rollout);
//# mouse pointer is placed over either zoom-in or zoom-out icon..
function process_zoom_rollover (event: MouseEvent): void
{
//trace("event.currentTarget : " + event.currentTarget.name );
event.currentTarget.addEventListener(Event.ENTER_FRAME, animate_Zoom);
}
//# mouse pointer is now move away from over any zoom icon.
function process_zoom_rollout (event: MouseEvent): void
{
event.currentTarget.removeEventListener(Event.ENTER_FRAME, animate_Zoom);
}
function animate_Zoom (event:MouseEvent) : void
{
//# scale by PERCENTAGE (width or height / 100), then multiply by some SPEED amount
if (event.currentTarget.name == "zoom_in") //increase width and height
{ pic.width += ((pic.width /100 ) * 1.75); pic.height += ((pic.height /100 ) * 1.75); }
if (event.currentTarget.name == "zoom_out") //decrease width and height
{ pic.width -= ((pic.width /100 ) * 1.75); pic.height -= ((pic.height /100 ) * 1.75); }
}
Second example will update zoom via mouse clicks...
zoom_in.addEventListener(MouseEvent.CLICK, process_zoom_click);
zoom_out.addEventListener(MouseEvent.CLICK, process_zoom_click);
//# mouse pointer is placed over either zoom-in or zoom-out icon.
function process_zoom_click (event:MouseEvent) : void
{
//trace("event.currentTarget : " + event.currentTarget.name );
if (event.currentTarget.name == "zoom_in") //increase width and height
{ pic.width += ((pic.width /100 ) * 1.75); pic.height += ((pic.height /100 ) * 1.75); }
if (event.currentTarget.name == "zoom_out") //decrease width and height
{ pic.width -= ((pic.width /100 ) * 1.75); pic.height -= ((pic.height /100 ) * 1.75); }
}

Related

How can I change Nested Class in actionscript 3

I'm working off an actionscript 3 code that pulls information from other actionscript 3's. The main code is Herbfight and it references 4 others (Bullets, bugs, Goodbugs and Sprayer). Below I'm trying to combine them all into one actionscript. The reason for this is that I want to pull it in as a symbol rather then having the flash file relate to the class.
The problem is it says I can't have nested classes. Any thoughts on how i can fix this? Below is my attempt to combine the code.
Thanks,
J
package {
import flash.display.;
import flash.events.;
import flash.utils.Timer;
import flash.text.TextField;
import flash.text.*;
import flash.utils.getTimer;
import flash.geom.Point;
public class herbfight_v004 extends MovieClip {
private var aagun:Sprayer;
private var airplanes:Array;
private var goodbug:Array;
private var bullets:Array;
private var upArrow, downArrow:Boolean;
private var nextPlane:Timer;
private var nextGbugs:Timer;
private var shotsLeft:int;
private var shotsHit:int;
private var Sprayer:MovieClip
private var Bullets:MovieClip
private var bugs:MovieClip
private var GooodBugs:MovieClip
public function startherbfight_v004() {
// init score
shotsLeft = 20;
shotsHit = 0;
showGameScore();
// create gun
aagun = new Sprayer();
addChild(aagun);
// create object arrays
airplanes = new Array();
bullets = new Array();
goodbug = new Array();
// listen for keyboard
stage.addEventListener(KeyboardEvent.KEY_DOWN,keyDownFunction);
stage.addEventListener(KeyboardEvent.KEY_UP,keyUpFunction);
// look for collisions
addEventListener(Event.ENTER_FRAME,checkForHits);
// start planes flying
setNextPlane();
setNextGbugs();
public function Sprayer() {
{
// animation time// initial location of gun
this.x = 410;
this.y = 380;
// movement
addEventListener(Event.ENTER_FRAME,moveGun);
}
public function moveGun(event:Event) {
// get time difference
var timePassed:int = getTimer()-lastTime;
lastTime += timePassed;
// current position
var newy = this.y;
// move to the left
if (MovieClip(parent).upArrow) {
newy -= speed*timePassed/1000;
}
// move to the right
if (MovieClip(parent).downArrow) {
newy += speed*timePassed/1000;
}
// check boundaries
if (newy < 65) newy = 65;
if (newy > 380) newy = 380;
// reposition
this.y = newy;
}
// remove from screen and remove events
public function deleteGun() {
parent.removeChild(this);
removeEventListener(Event.ENTER_FRAME,moveGun);
}
}
public function bugs(side:String, speed:Number, altitude:Number) {
{
if (side == "left") {
this.x = -50; // start to the left
dx = speed; // fly left to right
this.scaleX = 1; // reverse
} else if (side == "right") {
this.x = -50; // start to the right
dx = -speed; // fly right to left
this.scaleX = 1; // not reverse
}
this.y = altitude; // vertical position
// choose a random plane
this.gotoAndStop(Math.floor(Math.random()*4+1));
// set up animation
addEventListener(Event.ENTER_FRAME,movePlane);
lastTime = getTimer();
}
public function movePlane(event:Event) {
// get time passed
var timePassed:int = getTimer()-lastTime;
lastTime += timePassed;
// move plane
this.x += dx*timePassed/2000;
// check to see if off screen
if ((dx < 0) && (x < -50)) {
deletePlane();
} else if ((dx > 0) && (x > 350)) {
deletePlane();
}
}
// plane hit, show explosion
public function planeHit() {
removeEventListener(Event.ENTER_FRAME,movePlane);
MovieClip(parent).removePlane(this);
gotoAndPlay("explode");
}
// delete plane from stage and plane list
public function deletePlane() {
removeEventListener(Event.ENTER_FRAME,movePlane);
MovieClip(parent).removePlane(this);
parent.removeChild(this);
}
}
public function Bullets(x,y:Number, speed: Number) {
{
// set start position
this.x = x;
this.y = y;
// get speed
dx = speed;
// set up animation
lastTime = getTimer();
addEventListener(Event.ENTER_FRAME,moveBullet);
}
public function moveBullet(event:Event) {
// get time passed
var timePassed:int = getTimer()-lastTime;
lastTime += timePassed;
// move bullet
this.x += dx*timePassed/1000;
// bullet past top of screen
if (this.x < 0) {
deleteBullet();
}
}
// delete bullet from stage and plane list
public function deleteBullet() {
MovieClip(parent).removeBullet(this);
parent.removeChild(this);
removeEventListener(Event.ENTER_FRAME,moveBullet);
}
}
public function GoodBugs(side:String, speed:Number, altitude:Number) {
{
if (side == "left") {
this.x = -50; // start to the left
dx = speed; // fly left to right
this.scaleX = -1; // reverse
} else if (side == "right") {
this.x = -50; // start to the right
dx = -speed; // fly right to left
this.scaleX = -1; // not reverse
}
this.y = altitude; // vertical position
// choose a random Gbugs
this.gotoAndStop(Math.floor(Math.random()*2+1));
// set up animation
addEventListener(Event.ENTER_FRAME,moveGbugs);
lastTime = getTimer();
}
public function moveGbugs(event:Event) {
// get time passed
var timePassed:int = getTimer()-lastTime;
lastTime += timePassed;
// move Gbugs
this.x += dx*timePassed/2000;
// check to see if off screen
if ((dx < 0) && (x < -50)) {
deleteGbugs();
} else if ((dx > 0) && (x > 350)) {
deleteGbugs();
}
}
// Gbugs hit, show explosion
public function GbugsHit() {
removeEventListener(Event.ENTER_FRAME,moveGbugs);
MovieClip(parent).removeGbugs(this);
gotoAndPlay("explode");
}
// delete Gbugs from stage and Gbugs list
public function deleteGbugs() {
removeEventListener(Event.ENTER_FRAME,moveGbugs);
MovieClip(parent).removeGbugs(this);
parent.removeChild(this);
}
}
public function setNextPlane() {
nextPlane = new Timer(1000+Math.random()*1000,1);
nextPlane.addEventListener(TimerEvent.TIMER_COMPLETE,newPlane);
nextPlane.start();
}
public function newPlane(event:TimerEvent) {
// random side, speed and altitude
if (Math.random() > .2) {
var side:String = "left";
} else {
side = "right";
}
var altitude:Number = Math.random()*280+80;
var speed:Number = Math.random()*150+150;
// create plane
var p:bugs = new bugs(side,speed,altitude);
addChild(p);
airplanes.push(p);
// set time for next plane
setNextPlane();
}
public function setNextGbugs() {
nextGbugs = new Timer(1000+Math.random()*1000,1);
nextGbugs.addEventListener(TimerEvent.TIMER_COMPLETE,newGbugs);
nextGbugs.start();
}
public function newGbugs(event:TimerEvent) {
// random side, speed and altitude
if (Math.random() > .2) {
var side:String = "left";
} else {
side = "right";
}
var altitude:Number = Math.random()*280+80;
var speed:Number = Math.random()*150+150;
// create Gbugs
var p:GoodBugs = new GoodBugs(side,speed,altitude);
addChild(p);
goodbug.push(p);
// set time for next Gbugs
setNextGbugs();
}
// check for collisions
public function checkForHits(event:Event) {
for(var bulletNum:int=bullets.length-1;bulletNum>=0;bulletNum--){
for (var airplaneNum:int=airplanes.length-1;airplaneNum>=0;airplaneNum--) {
if (bullets[bulletNum].hitTestObject(airplanes[airplaneNum])) {
airplanes[airplaneNum].planeHit();
bullets[bulletNum].deleteBullet();
shotsHit++;
showGameScore();
break;
}
}
}
for(var bulletNum:int=bullets.length-1;bulletNum>=0;bulletNum--){
for (var GoodBugsNum:int= goodbug.length-1; GoodBugsNum>=0; GoodBugsNum--) {
if (bullets[bulletNum].hitTestObject(goodbug [GoodBugsNum])) {
goodbug [GoodBugsNum]. GbugsHit();
bullets[bulletNum].deleteBullet();
shotsHit--;
showGameScore();
break;
}
}
}
if ((shotsLeft == 0) && (bullets.length == 0)) {
endGame();
}
}
// key pressed
public function keyDownFunction(event:KeyboardEvent) {
if (event.keyCode == 38) {
upArrow = true;
} else if (event.keyCode == 40) {
downArrow = true;
} else if (event.keyCode == 32) {
fireBullet();
}
}
// key lifted
public function keyUpFunction(event:KeyboardEvent) {
if (event.keyCode == 38) {
upArrow = false;
} else if (event.keyCode == 40) {
downArrow = false;
}
}
// new bullet created
public function fireBullet() {
if (shotsLeft <= 0) return;
var b:Bullets = new Bullets(aagun.x,aagun.y,-300);
addChild(b);
bullets.push(b);
shotsLeft--;
showGameScore();
}
public function showGameScore() {
showScore.text = String("Score: "+shotsHit);
showShots.text = String("Shots Left: "+shotsLeft);
}
// take a plane from the array
public function removePlane(plane:bugs) {
for(var i in airplanes) {
if (airplanes[i] == plane) {
airplanes.splice(i,1);
break;
}
}
}
// take a plane from the array
public function removeGbugs(Gbugs:GoodBugs) {
for(var i in goodbug) {
if (goodbug[i] == Gbugs) {
goodbug.splice(i,1);
break;
}
}
}
// take a bullet from the array
public function removeBullet(bullet:Bullets) {
for(var i in bullets) {
if (bullets[i] == bullet) {
bullets.splice(i,1);
break;
}
}
}
// game is over, clear movie clips
public function endGame() {
// remove planes
for(var i:int=airplanes.length-1;i>=0;i--) {
airplanes[i].deletePlane();
}
for(var i:int= goodbug.length-1;i>=0;i--) {
goodbug [i].deleteGbugs();
}
airplanes = null;
goodbug = null
aagun.deleteGun();
aagun = null;
stage.removeEventListener(KeyboardEvent.KEY_DOWN,keyDownFunction);
stage.removeEventListener(KeyboardEvent.KEY_UP,keyUpFunction);
removeEventListener(Event.ENTER_FRAME,checkForHits);
nextPlane.stop();
nextPlane = null;
nextGbugs.stop();
nextGbugs = null;
gotoAndStop("gameover");
}
}
}

Flash AS3 Gravity and Jumping

Using ActionScript 3, I'm creating a platformer game on Flash CC. My code works fine, but I'm not satisfied with my character's jump.
I need a parabolic jump so he is able to step on other platforms, but at the moment my character only jumps in a straight motion and falls too fast to the floor. My character should fall slow enough so I can press the left and right buttons while they're falling.
In the below code, I'm using mouse events because I will be publishing it on my mobile device.
My character has an instance name of SDeer:
import flash.events.MouseEvent;
var xdir: int = 0;
var ydir: int = 0;
var speed: int = 10;
var jumping = false;
var gravity: int = 1.5;
var floor : int = 400;
var LeftUp : Boolean;
var RightUp : Boolean;
SDeer.gotoAndStop ('Still');
RightButton.addEventListener (MouseEvent.MOUSE_DOWN, onRight);
JumpButton.addEventListener (MouseEvent.MOUSE_DOWN, onJump);
LeftButton.addEventListener (MouseEvent.MOUSE_DOWN, onLeft);
LeftButton.addEventListener (MouseEvent.MOUSE_UP, LeftOnUp);
RightButton.addEventListener (MouseEvent.MOUSE_UP, RightOnUp);
DuckButton.addEventListener (MouseEvent.MOUSE_DOWN, onDuck);
addEventListener(MouseEvent.MOUSE_UP, onUp);
addEventListener(Event.ENTER_FRAME, onEnterFrame);
function onRight (e:MouseEvent): void {
SDeer.gotoAndStop ('Running');
xdir = 1;
}
function onJump (e:MouseEvent): void {
if (LeftUp == true){
SDeer.gotoAndStop ('JumpLeft')
}
else {
SDeer.gotoAndStop ('Jumping');
}
ydir = -1;
}
function onDuck (e:MouseEvent): void {
if (LeftUp == true && RightUp == false){
SDeer.gotoAndStop ('DuckLeft')
}
else if (RightUp == true && LeftUp == false){
SDeer.gotoAndStop ('Duck');
}
ydir = 1;
}
function onUp (e:MouseEvent): void {
if (LeftUp == true && RightUp == false) {
SDeer.gotoAndStop ('LeftStill');
}
else if (RightUp == true && LeftUp == false){
SDeer.gotoAndStop ('Still');
}
xdir = 0;
ydir = 0;
}
function onLeft (e:MouseEvent) : void {
SDeer.gotoAndStop ('RunLeft');
xdir = -1;
}
function LeftOnUp (e:MouseEvent) : void {
LeftUp = true;
RightUp = false;
}
function RightOnUp (e:MouseEvent) : void {
LeftUp = false;
RightUp = true;
}
function onEnterFrame(e: Event): void {
SDeer.x += xdir * speed;
SDeer.y += ydir * speed;
}
//Hit check
stage.addEventListener(Event.ENTER_FRAME, hitCheck);
function hitCheck(event: Event): void {
SDeer.y += gravity;
if (SDeer.y + SDeer.height / 2 < floor){
gravity++;
}
else {
gravity = 0;
SDeer.y = floor - SDeer.height / 2;
}
}
Don't reset the gravity. Instead, have a velocity affected by gravity. For example...
var gravity:Number = 9.8; // meters/second/second standard, but can be whatever
var jumpVel:Number = 0;
function onJump( e:MouseEvent ) : void
{
if (LeftUp == true){
SDeer.gotoAndStop ('JumpLeft')
}
else {
SDeer.gotoAndStop ('Jumping');
}
jumpVel Number = -20; // 45mph!
}
...and in your ENTER_FRAME handler...
if ( jumpVel != 0 )
{
SDeer.y += jumpVel / stage.frameRate;
jumpVel += gravity / stage.frameRate;
if ( SDeer.y + SDeer.height >= floor )
{
jumpVel = 0;
SDeer.y = floor - SDeer.height;
}
}
I have a related answer at ActionScript 3, How to get character to jump for longer

Action Script 3. Platform game physics glitch (gravity)

when my player touches the floor, he is unable to move because he is on the floor and being incremented up.
In the main class I have the movement
private function processMovement():void
{
if (touchingGround)
{
if (upKey)
{
character.jumpUp();
}
if (leftKey)
{
character.moveLeft();
}
if (rightKey)
{
character.moveRight();
}
if (!leftKey && !rightKey && !upKey)
{
character.dontMove();
}
}
}
Then in the character class you will see this.
public class player extends OnGround
{
public var canJumpAn:Boolean;
public var attackAn:Boolean;
public var jumpheight:Number = 18;
public function player()
{
addEventListener(Event.ADDED_TO_STAGE, onAdd);
}
private function onAdd(e: Event): void
{
removeEventListener(Event.ADDED_TO_STAGE, onAdd);
}
public function moveLeft():void
{
//decrease VELOCITY
xV -= 2;
if (xV > -7)
{
xV = -7;
}
this.gotoAndStop("run");
//add this to the Mc . x pos baby.
this.x += xV;
this.scaleX = -1;
charIsrunning = true;
}
public function moveRight():void
{
//increase VELOCITY
xV += 2;
if (xV > 7)
{
xV = 7;
}
this.gotoAndStop("run");
//add this to the Mc . x pos baby.
this.x += xV;
this.scaleX = 1;
charIsrunning = true;
}
public function dontMove():void
{
//if no button presses then do this
this.gotoAndStop("stop");
//slowd down ball
xV *= friction;
charIsrunning = false;
isDefending = false;
//stop the ball if you're not moving
if (xV > - 1 && xV < 1)
{
xV = 0;
}
}
override public function positionOnLand():void
{
isJumping = false;
///=gotoAndStop(1);
}
public function defend():void
{
isDefending = true;
this.gotoAndStop("defend");
charIsrunning = false;
}
public function attack():void
{
this.gotoAndStop("attack");
}
public function jumpUp():void
{
if (!isJumping)
{
isJumping = true;
this.gotoAndStop("jump");
//
}
}
}
}
OnGround is another class that player extends, as you can see.
public class OnGround extends MovieClip
{
public var grav:Number;
public var friction:Number;
public var xV:Number;
public var yV:Number;
protected var charIsrunning:Boolean;
protected var isDefending:Boolean;
protected var isJumping:Boolean;
public function OnGround()
{
addEventListener(Event.ADDED_TO_STAGE, init)
charIsrunning = false;
isDefending = false;
//gotoAndStsop("jump");
}
private function init(e:Event):void
{
removeEventListener(Event.ADDED_TO_STAGE, init);
//gravity
grav = 0.6;
//y velocity
yV = 0;
//x velocity
xV = 0;
//
friction = 0.9;
addEventListener(Event.ENTER_FRAME, fall);
}
private function fall(e:Event):void
{
//add grav to y VELOCITY
yV += grav;
trace(yV);
this.y += yV
}
public function incrementUp():void
{
this.y -= 0.1;
//trace("incrementing");
}
public function keepOnGround():void
{
//trace("onGroundBitch");
grav = 0;
yV = 0;
positionOnLand();
}
public function positionOnLand():void
{
//overide
}
}
}
This is a function that's in the main class
for (var c:int = 0; c < childrenOnStage; c++)
{
if (getChildAt(c).name == "player")
{
if (ground.level1Ground.hitTestPoint(getChildAt(c).x + 13, getChildAt(c).y, true) || ground.level1Ground.hitTestPoint(getChildAt(c).x - 13, getChildAt(c).y, true))
{
getChildAt(c).y --;
//OnGround(getChildAt(c)).incrementUp();
OnGround(getChildAt(c)).keepOnGround();
touchingGround = true;
}
else
{
touchingGround = false;
}
The problem is that when the player touches the ground then it's y position is incremented until it isn't touching the ground and then it's suppose to be kept on the ground by turning grav to = 0 and y velocity to 0.
This means gravity is turned off and the players y position will not shift up (when I jump)
or when go down to be kept on ground.
I would appreciate it if someone can lend me a hand or point me in the correct direction.
I'm not sure why you'd have a gravity value per object unless you really intend to have different object instances have individual gravities.
If not I'd reference a gravity constant instead.
Is anti-gravity a feature of the game? if not then I'd avoid setting gravity to 0. It may 'work' (to an extent) but it's not a good model/abstraction of reality.
Rather, what I would do is seperate the force applied and the current momentum:
The (downward) force of gravity is applied at all times.
When you're standing on the ground an upward force equal and opposite to gravity is applied.
When you jump, add a one-off instance of upward force.
Use the current forces to change the current momentum and use the current momentum to change the position.

To much FPS drop

http://www.fastswf.com/USUAp00
When i scale my procedural generated map based off a perlin noise map to a bigger size, so i can place a character on the map and actually navigate it (moving the map around the player instead of the player around the map), it gets major fps drop.
Test for yourself with the provided link, the higher the scale or map width/height is increased the more it lags while walking. I understand this is allot of data blocks to move
Is there a better way to go about moving my player around?
Would adding the spawned objects to an object pool help? I don't think it would
Is it possible to split the map into segments after generation and load certain segments based off your x,y?
World class: //handles spawning the map
http://pastebin.com/CfMDBWeR
Level class: // handles moving the map around
public class Level extends MovieClip
{
var world:World;
protected var goin:Vector.<int> = new Vector.<int>();
protected var moveSpeed:int;
protected var MAP_SCALE:int;
public function Level()
{
MAP_SCALE = GlobalCode.MAP_SCALE;
trace("level")
for(var i:int = 0; i < 4; i++){
goin[i]=0;
}
world = new World(this);
addEventListener(Event.ENTER_FRAME, update);
addEventListener(Event.ADDED_TO_STAGE, init);
addEventListener(Event.REMOVED_FROM_STAGE, cleanUp);
moveSpeed = 10;
// constructor code
}
protected function init(e:Event)
{
stage.addEventListener(KeyboardEvent.KEY_DOWN, keyPressed);
stage.addEventListener(KeyboardEvent.KEY_UP, keyReleased);
}
protected function cleanUp(e:Event)
{
stage.removeEventListener(KeyboardEvent.KEY_DOWN, keyPressed);
stage.removeEventListener(KeyboardEvent.KEY_UP, keyReleased);
}
protected function keyPressed(k:KeyboardEvent)
{
if (k.keyCode == Keyboard.W)
{
goin[0] = 1;
}
if (k.keyCode == Keyboard.S)
{
goin[1] = 1;
}
if (k.keyCode == Keyboard.A)
{
goin[2] = 1;
}
if (k.keyCode == Keyboard.D)
{
goin[3] = 1;
}
}
protected function MovePlayer(){
if (goin[0] == 1)
{
world.worldTiles.y += moveSpeed;
}
if (goin[1] == 1)
{
world.worldTiles.y -= moveSpeed;
}
if (goin[2] == 1)
{
world.worldTiles.x += moveSpeed;
}
if (goin[3] == 1)
{
world.worldTiles.x -= moveSpeed;
}
}
protected function keyReleased(k:KeyboardEvent)
{
if (k.keyCode == Keyboard.W)
{
goin[0] = 0;
}
if (k.keyCode == Keyboard.S)
{
goin[1] = 0;
}
if (k.keyCode == Keyboard.A)
{
goin[2] = 0;
}
if (k.keyCode == Keyboard.D)
{
goin[3] = 0;
}
}
public function update(e:Event)
{
world.worldTiles.scaleX = MAP_SCALE;
world.worldTiles.scaleY = MAP_SCALE;
MovePlayer();
}
}
Stage Class: The class actually connected to the stage, handles frame switching
public class Stage extends MovieClip {
private var targetFrame:String;
public function Stage() {
targetFrame = "Menu";
// constructor code
}
private function gotoLabel(desiredLabel:String)
{
for (var i=0; i<currentLabels.length; i++)
{
if (currentLabels[i].name == desiredLabel)
{
gotoAndPlay(desiredLabel);
return;
}
}
trace("Requested frame missing!");
}
public function generateMap(m:MouseEvent){
GlobalCode.TILE_SIZE = int(tileSizeText.text);
GlobalCode.MAP_HEIGHT = int(mapHeightText.text);
GlobalCode.MAP_WIDTH = int(mapWidthText.text);
GlobalCode.MAP_SCALE = int(mapScaleText.text);
gotoLabel("Game");
}
private function doneLoading(m:MouseEvent)
{
//set targetFrame
gotoLabel("Menu");
}
}

AS3 - Friction(?) causing Movie Clip to jump, temporarily alter path (playable SWF included)

Im making a game in FlashBuilder where the player controls a movieclip (_character) around the stage with the arrows or WASD. On the stage there are squares/boxes with collision detection and a 50 pixel border around.
While testing Ive noticed that if I hold a direction key, then switch to another AND the MovieClip is travelling past a gap in the boxes, the movieclip will jump a few pixels in the previous pressed direction, then back down again quickly.
It’s a split second flicker but creates a distracting jumpy, stutter effect. This happens with multiple key presses, but not if I press a button, release it, then press the other direction button.
The yellow crosses on the image below show some of the areas where this happens.
The larger the Friction number in my code, the more noticeable it is. But if I lower the friction too much (0.8ish) The Movie Clip moves too slowly around the stage and the game is unplayable.
I currently have the friction at 0.88 which lessens the jump, but it is still noticeable. Does anyone know why this is happening and/or how I could stop it? (while keeping the fluid movement of the movieclip of course.)
This SWF shows friction at 0.94 so the effect is very noticeable, especially in the top right corner. (Move character around stage with arrows or WASD.)
0.94 Friction SWF
This SWF has friction at 0.88, less noticeable, but it still happens!
0.88 Friction SWF
This problem doesn’t happen if I’m going UP to DOWN or LEFT to RIGHT, traveling past gaps. It only happens when two diagonal linked direction buttons are pressed, traveling past a gap.
If I travel UP then LEFT the MovieClip will jump upwards. If I travel DOWN, then LEFT and go across a gap the movieclip will jump a few pixels downwards, like the character is squatting(?)
Current Code
Rookies game/Application class is used as a level switcher to put levelOne onto the stage.
package
{
import flash.display.MovieClip;
import flash.display.Sprite;
import flash.events.Event;
[SWF(width="650", height="450", backgroundColor="#FFFFFF", frameRate="60")]
public class RookiesGame extends Sprite
{
private var _levelOne:LevelOne;
//public static var gameMute:Boolean = false;
public function RookiesGame()
{
_levelOne = new LevelOne(stage);
stage.addChild(_levelOne);
stage.addEventListener("levelOneComplete",levelTwoSwitchHandler);
}
private function levelTwoSwitchHandler(event:Event):void
{
}
}
}
Level One contains most of the code, and majority of the work.
package
{
//import statements
public class LevelOne extends Sprite
{
//Declare the variables to hold the game objects
private var _character:Character = new Character();
private var _background:Background = new Background();
private var _box1:Box = new Box();
//Other box vars
//A variable to store the reference to the stage from the application class
private var _stage:Object;
//Control System
private var _bUp:Boolean = false;
private var _bDown:Boolean = false;
private var _bLeft:Boolean = false;
private var _bRight:Boolean = false;
public function LevelOne(stage:Object)
{
_stage = stage;
this.addEventListener(Event.ADDED_TO_STAGE, addedToStageHandler);
}
private function addedToStageHandler(event:Event):void
{
startGame();
this.removeEventListener(Event.ADDED_TO_STAGE, addedToStageHandler);
}
private function startGame():void
{
addGameObjectToLevel(_background, 0, 0);
addGameObjectToLevel(_box1, 300, 200);
//Other boxes added to Level
//Add character
this.addChild(_character);
_character.x = 300;
_character.y = 50;
_character.gotoAndStop(1);
playGame();
}
private function playGame():void
{ //EVENT LISTENERS////////////////////////
_stage.addEventListener(KeyboardEvent.KEY_DOWN, keyDownHandler);
_stage.addEventListener(KeyboardEvent.KEY_UP, keyUpHandler);
this.addEventListener(Event.ENTER_FRAME, enterFrameHandler);
}
private function enterFrameHandler(event:Event):void
{
_character.accelerationX = 0;
_character.accelerationY = 0;
_character.friction = 0.94;
var _updown:Boolean=Boolean(!(_bUp==_bDown));
var _leftright:Boolean=Boolean(!(_bLeft==_bRight));
if (!_updown && !_leftright)
{ // not moving anywhere
_character.gotoAndStop(1);
_character.accelerationX = 0;
_character.accelerationY = 0;
_character.friction = 0.94;
_character.vy=0;
_character.vx=0;
}
else
{
if (_bUp)
{
_character.accelerationY = -0.5;
_character.gotoAndStop(2);
}
else if (_bDown)
{
_character.accelerationY = 0.5;
_character.gotoAndStop(3);
}
if (_bLeft)
{
_character.accelerationX = -0.5;
_character.gotoAndStop(4);
}
else if (_bRight)
{
_character.accelerationX = 0.5;
_character.gotoAndStop(5);
}
}
//Apply friction
_character.vx *= _character.friction;
_character.vy *= _character.friction;
//Apply acceleration
_character.vx += _character.accelerationX;
_character.vy += _character.accelerationY;
//Limit the speed
if (_character.vx > _character.speedLimit)
{
_character.vx = _character.speedLimit;
}
if (_character.vx < -_character.speedLimit)
{
_character.vx = -_character.speedLimit;
}
if (_character.vy > _character.speedLimit)
{
_character.vy = _character.speedLimit;
}
if (_character.vy < -_character.speedLimit)
{
_character.vy = -_character.speedLimit;
}
//Force the velocity to zero after it falls below 0.1
if (Math.abs(_character.vx) < 0.1)
{
_character.vx = 0;
}
if (Math.abs(_character.vy) < 0.1)
{
_character.vy = 0;
}
//Move the character
_character.x += _character.vx;
_character.y += _character.vy;
checkStageBoundaries(_character);
//Box Collisions
Collision.block(_character,_box1);
//All other box collisions
}
private function checkStageBoundaries(gameObject:MovieClip):void
{
if (gameObject.x < 50)
{
gameObject.x = 50;
}
if (gameObject.y < 50)
{
gameObject.y = 50;
}
if (gameObject.x + gameObject.width > _stage.stageWidth - 50)
{
gameObject.x = _stage.stageWidth - gameObject.width - 50;
}
if (gameObject.y + gameObject.height > _stage.stageHeight - 50)
{
gameObject.y = _stage.stageHeight - gameObject.height - 50;
}
}
public function replay():void
{
_stage.removeEventListener(KeyboardEvent.KEY_DOWN, keyDownHandler);
_stage.removeEventListener(KeyboardEvent.KEY_UP, keyUpHandler);
this.removeEventListener(Event.ENTER_FRAME, enterFrameHandler);
startGame();
}
private function keyDownHandler(event:KeyboardEvent):void
{
if (event.keyCode == Keyboard.LEFT || event.keyCode == 65 )
{
_bLeft=true;
}
else if (event.keyCode == Keyboard.RIGHT || event.keyCode == 68)
{
_bRight=true;
}
else if (event.keyCode == Keyboard.UP || event.keyCode == 87 )
{
_bUp=true;
}
else if (event.keyCode == Keyboard.DOWN || event.keyCode == 83)
{
_bDown=true;
}
if (event.keyCode == Keyboard.ENTER)
{
replay();
}
}
private function keyUpHandler(event:KeyboardEvent):void
{
if (event.keyCode == Keyboard.LEFT || event.keyCode == Keyboard.RIGHT
|| event.keyCode == 65 || event.keyCode == 68)
{
_bLeft=false;
_bRight=false;
}
else if (event.keyCode == Keyboard.DOWN || event.keyCode == Keyboard.UP
|| event.keyCode == 87 || event.keyCode == 83 )
{
_bUp=false;
_bDown=false;
}
}
private function addGameObjectToLevel(gameObject:Sprite, xPos:int, yPos:int):void
{
this.addChild(gameObject);
gameObject.x = xPos;
gameObject.y = yPos;
}
}
}
_character is an instance of the Character Class.
The SWF has five key frames, each with an animation inside, which plays when the four direction buttons are pressed, plus the red stationary animation when nothing is being pressed.
package
{
import flash.display.MovieClip;
import flash.display.DisplayObject
[Embed(source="../swfs/characterResource.swf", symbol="Character")]
public class Character extends MovieClip
{
//Public properties
public var vx:Number = 0;
public var vy:Number = 0;
public var accelerationX:Number = 0;
public var accelerationY:Number = 0;
public var speedLimit:Number = 4;
public var friction:Number = 0.94;
public function Character()
{
}
}
}
The Box and Background classes are the same, they just embed the png and add the sprites. Note that the grid background is a single image. The game is not tile based..
And finally the Collision Class. When _character collides with a box, it calls the Collision.block function.
package
{
import flash.display.Sprite;
public class Collision
{
static public var collisionSide:String = "";
public function Collision()
{
}
static public function block(r1:Sprite, r2:Sprite):void
{
//Calculate the distance vector
var vx:Number
= (r1.x + (r1.width / 2))
- (r2.x + (r2.width / 2));
var vy:Number
= (r1.y + (r1.height / 2))
- (r2.y + (r2.height / 2));
//Check whether vx
//is less than the combined half widths
if(Math.abs(vx) < r1.width / 2 + r2.width / 2)
{
//A collision might be occurring! Check
//whether vy is less than the combined half heights
if(Math.abs(vy) < r1.height / 2 + r2.height / 2)
{
//A collision has ocurred! This is good!
//Find out the size of the overlap on both the X and Y axes
var overlap_X:Number
= r1.width / 2
+ r2.width / 2
- Math.abs(vx);
var overlap_Y:Number
= r1.height / 2
+ r2.height / 2
- Math.abs(vy);
//The collision has occurred on the axis with the
//*smallest* amount of overlap. Let's figure out which
//axis that is
if(overlap_X >= overlap_Y)
{
//The collision is happening on the X axis
//But on which side? _v0's vy can tell us
if(vy > 0)
{
collisionSide = "Top";
//Move the rectangle out of the collision
r1.y = r1.y + overlap_Y;
}
else
{
collisionSide = "Bottom";
//Move the rectangle out of the collision
r1.y = r1.y - overlap_Y;
}
}
else
{
//The collision is happening on the Y axis
//But on which side? _v0's vx can tell us
if(vx > 0)
{
collisionSide = "Left";
//Move the rectangle out of the collision
r1.x = r1.x + overlap_X;
}
else
{
collisionSide = "Right";
//Move the rectangle out of the collision
r1.x = r1.x - overlap_X;
}
}
}
else
{
//No collision
collisionSide = "No collision";
}
}
else
{
//No collision
collisionSide = "No collision";
}
}
}
}
Any help would be much appreciated. I'm a beginner so its always possible the problem is something simple I've missed.
Im also asking a question about the unwanted bobbing of the animations. If any of that info helps you, or you're smart enough to know the solution to that too, the question is HERE
have you tried this?
if (event.keyCode == Keyboard.LEFT || event.keyCode == 65 )
{
_bLeft=true;
_bRight=false;
_bUp=false;
_bDown=false;
}
else if (event.keyCode == Keyboard.RIGHT || event.keyCode == 68)
{
_bRight=true;
_bLeft=false;
_bUp=false;
_bDown=false;
}
else if (event.keyCode == Keyboard.UP || event.keyCode == 87 )
{
_bUp=true;
_bRight=false;
_bLeft=false;
_bDown=false;
}
else if (event.keyCode == Keyboard.DOWN || event.keyCode == 83)
{
_bDown=true;
_bRight=false;
_bLeft=false;
_bUp=false;
}