Breakout with Flash: I need help to improve my Brick n Ball collision - actionscript-3

I've been stuck on this problem for a very long time now, I've searched around alot and tried stuff, but nothing works. Some explanations are just very hard for me to understand as Im pretty new to programming overall and got alot to learn.
I have two problems
1: The ball wont collide with the bricks sometimes when the speed is too fast.
2: The ball is capable of hitting 2 bricks.
Both problems is related to the fact that 60 fps isnt enough for my type of collision detection to work properly.
I just need someone to explain in a simple way as possible what I need to do to make a collision detection that will prevent this from happen.
Here's my current collision code:
private function checkCollision(): void {
grdx = Math.floor((ball.x) / 28);
grdy = Math.floor((ball.y) / 14);
ngrdx = Math.floor((ball.x + dx) / 28);
ngrdy = Math.floor((ball.y + dy) / 14);
var flipX: Boolean = false;
var flipY: Boolean = false;
if ((grdy <= level.length - 1) &&
(ngrdy <= level.length - 1) &&
(grdy >= 0 && ngrdy >= 0)) {
if (testBlock(grdx, ngrdy)) {
flipY = true;
paddleFlag = 1;
}
if (testBlock(ngrdx, grdy)) {
flipX = true;
paddleFlag = 1;
}
if (testBlock(ngrdx, ngrdy)) {
flipX = true;
flipY = true;
paddleFlag = 1;
}
dx *= flipX ? -1 : 1;
dy *= flipY ? -1 : 1;
}
}
private function testBlock(xPos: int, yPos: int): Boolean {
if (level[yPos][xPos] > 0 && level[yPos][xPos] != 13) {
trace("hit on X,Y");
level[yPos][xPos] = 0;
breakBlock("Block_" + yPos + "_" + xPos);
trace("Block: " + totalBreaks + " / " + totalBlocks);
return true;
}
return false;
}
private function breakBlock(blockName: String): void {
if (this.getChildByName(blockName)) {
this.removeChild(this.getChildByName(blockName));
totalBreaks++;
}
}
Thank you and sorry for my bad english, its not my motherlanguage.

One solution is to move the ball in smaller iterations, multiple times in a given frame.
For example, and I am giving this solution assuming that you are moving the ball based on the time elapsed from the last frame.
Suppose that 30 milliseconds have elapsed since the last frame update. In that case you would update the movement/collision twice in that frame using 15 millisecond as your time elapsed.
The higher resolution of collision you want, the more iterations you would do.
Here's an example :
// class declarations
var lastFrame:Number;
var iterationsPerFrame:int;
function startGame():void
{
// lets specify 3 updates per frame
iterationsPerFrame = 3;
// save initial time
lastFrame = getTimer();
// create your listener
addEventListener(Event.ENTER_FRAME, update);
}
function update(e:Event):void
{
var currentFrame:Number = getTimer();
var deltaTime:Number = (currentFrame - lastFrame)/1000;
var iterationDelta:Number = deltaTime/iterationsPerFrame;
for (var index:int = 0;index < iterationsPerFrame;index++)
{
// I'm assuming dx,dy are the velocity of the ball, in pixels per second
ball.x += dx * iterationDelta;
ball.y += dy * iterationDelta;
// check collision
}
// set lastFrame to the currentFrame time, preparing for next frame
lastFrame = currentFrame;
// after this, your frame is going to render
}

You could work out how far the ball travels each frame (A) based on its speed, how far the ball is from the paddle (B) and if A > B manually trigger a collision that frame.
You're essentially checking every bricks X and Y coordinate to the balls X and Y coordinate, so if the bricks are stored in an array this becomes: Sqrt( Sqrd(p2.x - p1.x) + Sqrd(p2.y - p1.y))
for(var i=0; i<brickArray.length; i++)
{
var distance:Number = Math.sqrt((brickArray[i].x - ball.x) * (brickArray[i].x - ball.x) +
(brickArray[i].y - ball.y) * (brickArray[i].y - ball.y));
}
This is a very good tutorial on high speed collison detection:
http://www.newgrounds.com/bbs/topic/1072673

Related

Actionscript 3.0 Mouse trail snake game logic

I am developing a game in actionscript 3.0 (adobe flash) similar to this https://www.tvokids.com/preschool/games/caterpillar-count. I have the code for dragging the head of the snake in the direction of the mouse. However, I do not know how do I add the body of the snake and make it follow the path of the head. Following is my code to drag movieclip in the direction of the mouse :
var _isActive = true;
var _moveSpeedMax:Number = 1000;
var _rotateSpeedMax:Number = 15;
var _decay:Number = .98;
var _destinationX:int = 150;
var _destinationY:int = 150;
var _dx:Number = 0;
var _dy:Number = 0;
var _vx:Number = 0;
var _vy:Number = 0;
var _trueRotation:Number = 0;
var _player;
var i;
createPlayer();
stage.addEventListener(MouseEvent.MOUSE_DOWN, onDown);
function createPlayer():void{
_player = new head();
_player.x = stage.stageWidth / 2;
_player.y = stage.stageHeight / 2;
stage.addChild(_player);
}
function onDown(e:MouseEvent):void{
_isActive = true;
stage.addEventListener(MouseEvent.MOUSE_MOVE, onMove);
stage.addEventListener(MouseEvent.MOUSE_UP, onUp);
}
function onMove(e:MouseEvent):void{
updatePosition(_player);
updateRotation(_player);
}
function onUp(e:MouseEvent):void{
_isActive = false;
stage.removeEventListener(MouseEvent.MOUSE_MOVE, onMove);
stage.removeEventListener(MouseEvent.MOUSE_UP, onUp);
}
function updatePosition(mc):void
{
// check if mouse is down
if (_isActive)
{
// update destination
_destinationX = stage.mouseX;
_destinationY = stage.mouseY;
// update velocity
_vx += (_destinationX - mc.x) / _moveSpeedMax;
_vy += (_destinationY - mc.y) / _moveSpeedMax;
}
else
{
// when mouse is not down, update velocity half of normal speed
_vx += (_destinationX - mc.x) / _moveSpeedMax * .25;
_vy += (_destinationY - mc.y) / _moveSpeedMax * .25;
}
// apply decay (drag)
_vx *= _decay;
_vy *= _decay;
// if close to target, slow down turn speed
if (getDistance(_dx, _dy) < 50)
{
_trueRotation *= .5;
}
// update position
mc.x += _vx;
mc.y += _vy;
}
function updateRotation(mc):void
{
// calculate rotation
_dx = mc.x - _destinationX;
_dy = mc.y - _destinationY;
// which way to rotate
var rotateTo:Number = getDegrees(getRadians(_dx, _dy));
// keep rotation positive, between 0 and 360 degrees
if (rotateTo > mc.rotation + 180) rotateTo -= 360;
if (rotateTo < mc.rotation - 180) rotateTo += 360;
// ease rotation
_trueRotation = (rotateTo - mc.rotation) / _rotateSpeedMax;
// update rotation
mc.rotation += _trueRotation;
}
function getDistance(delta_x:Number, delta_y:Number):Number
{
return Math.sqrt((delta_x*delta_x)+(delta_y*delta_y));
}
function getRadians(delta_x:Number, delta_y:Number):Number
{
var r:Number = Math.atan2(delta_y, delta_x);
if (delta_y < 0)
{
r += (2 * Math.PI);
}
return r;
}
function getDegrees(radians:Number):Number
{
return Math.floor(radians/(Math.PI/180));
}
The script below will not miraculously work on its own, however it has all the logic you need, well-explained. It makes a chain of any length follow its head by certain rules. I used the same principle here many years ago: http://delimiter.ru/games/25-lines/alone.html
// This one will represent the Mouse position.
var Rat:Sprite = new Sprite;
// The ordered list of chain elements.
// It all starts with the Mouse.
var Snake:Array = [Rat];
// Call this one each time you want to
// extend the snake with the piece of tail.
function addTail(aPiece:DisplayObject):void
{
// Get the last snake element.
var lastPiece:DisplayObject = Snake[Snake.length - 1];
// Sync the tail coordinates.
aPiece.x = lastPiece.x;
aPiece.y = lastPiece.y;
// Add the new piece to the snake.
Snake.push(aPiece);
}
// Add the pre-defined head as the first element.
addTail(SnakeHead);
// Now start following the Mouse.
addEventListener(Event.ENTER_FRAME, onFrame);
// Fires every frame and adjusts the whole snake, if needed.
function onFrame(e:Event):void
{
// Sync the attractor point with the Mouse.
Rat.x = mouseX;
Rat.y = mouseY;
// Now lets make each piece follow the previous piece,
// one by one, starting from the head, down to the tail.
for (var i:int = 1; i < Snake.length; i++)
{
followOne(Snake[i - 1], Snake[i]);
}
}
function followOne(A:DisplayObject, B:DisplayObject):void
{
// Think of these values as of vector
// pointing from B position to A position.
var dx:Number = A.x - B.x;
var dy:Number = A.y - B.y;
// Figure out the distance between the given pieces.
var aDist:Number = Math.sqrt(dx * dx + dy * dy);
// Do nothing if pieces are closer than 20 px apart.
// You can change this value to make snake shorter or longer.
if (aDist < 20)
{
return;
}
// This literally means "eat one tenth of the distance
// between me and the previous piece". If you want pieces
// to follow each other with more vigor, reduce this value,
// if you want the whole snake to slither smoothly, increase it.
B.x += dx / 10;
B.y += dy / 10;
// Rotate the B piece so it would look right into A's direction.
// Well, unless your pieces are round and look all the same.
B.rotation = Math.atan2(dy, dx) * 180 / Math.PI;
}

How can I code an object to spawn onto the stage in the Actions panel?

I am trying to introduce a new ball into my pong game, sort of like a power up. I am writing all of my code in the Actions panel in the first frame. The new ball should appear on the stage and start moving around randomly like the original ball. Although I am using a code snippet and not .as file. So all of my code is in the Actions panel(Accessed by pressing f9).
I would also like my dynamic text box to merge with the stage colour so that you can't see the white background.
I can't show you what the fla looks like because I have less than 10 reputation, but the dynamic text box will not merge into the background and instead has a white surrounding. This hides the ball when the ball goes up.
import flash.events.Event;
import flash.ui.Mouse;
//hide mouse
Mouse.hide();
init(); //initialises everything
var bSpeedX:int = -3.5;
var bSpeedY:int = -2.5;
// assign a maximum speed to the AI
var compPaddleSpeed:int = 3.5;
var pScore:int = 0;
var cScore:int = 0;
// Updates the score
function scoreUpdate():void {
playerScore.text = ("Player Score: " + pScore);
computerScore.text = ("AI Score: " + cScore);
}
function init():void //tells flash not to return values
{
stage.addEventListener(Event.ENTER_FRAME, loop);
}
/*we want the ySpeed to be larger if there
is a greater difference between the y
positions of the ball and paddle, so I started with
(gameBallY-padY). To convert this difference
into a number between -1 and 1, I divided
this number by 25, which
is half the height of the paddle. Finally, I wanted
the ySpeed to be more powerful than
just -1 to 1, and after a bit of trial and error
I decided to times by 5 at the end
to change the total magnitude of the new ySpeed.*/
//defying the laws of Physics
function calculategameBallAngle(padY:Number, gameBallY:Number):Number
{
var ySpeed:Number = 5 * ((gameBallY-padY) / 25 );
return ySpeed;
}
//main loop
function loop(e:Event):void
{
//makes the paddle track the mouse
playerPaddle.y = mouseY;
//paddle AI
if(compPaddle.y < gameBall.y - 10){
compPaddle.y += compPaddleSpeed;//make it go up
} else if(compPaddle.y > gameBall.y + 10){
compPaddle.y -= compPaddleSpeed;//make it go down
}
//Collisions
if( playerPaddle.hitTestObject(gameBall) == true ){
if(bSpeedX < 0){
bSpeedX *= -1;
bSpeedY = calculategameBallAngle(playerPaddle.y, gameBall.y);
}
} else if(compPaddle.hitTestObject(gameBall) == true ){
if(bSpeedX > 0){
bSpeedX *= -1;
bSpeedY = calculategameBallAngle(compPaddle.y, gameBall.y);
}
}
//makes the gameBall move
gameBall.x += bSpeedX; //each frame, we add the bSpeedX to the ball's x position.
gameBall.y += bSpeedY; //same for the bSpeedY to the ball's y postion.
// checks to see if the ball misses the paddle
if(gameBall.x <= gameBall.width/2){
gameBall.x = gameBall.width/2;
bSpeedX *= -1;
cScore ++;
scoreUpdate();
//keeps the ball within the stage
} else if(gameBall.x >= stage.stageWidth-gameBall.width/2){
gameBall.x = stage.stageWidth-gameBall.width/2;
bSpeedX *= -1;
pScore ++;
scoreUpdate();
}
if(gameBall.y <= gameBall.height/2){
gameBall.y = gameBall.height/2;
bSpeedY *= -1;
}
else if(gameBall.y >= stage.stageHeight-gameBall.height/2){
gameBall.y = stage.stageHeight-gameBall.height/2;
bSpeedY *= -1;
}
//-------------------------------------------------------
//keeps the player paddle within the stage
//check if paddle is above top of the screen
if(playerPaddle.y - playerPaddle.height/2 < 0){
playerPaddle.y = playerPaddle.height/2;
} else if(playerPaddle.y + playerPaddle.hieght/2 > stage.stageHeight){
playerPaddle.y = stage.stageHeight - playerPaddle.height/2;
//check if paddle is below bottom of the screen
} else if(playerPaddle.y + playerPaddle.height/2 > stage.stageHeight){
playerPaddle.y = stage.stageHeight - playerPaddle.height/2;
}
}
If you only want your ball to be replaced with new one which has diffrent grphics and/or speed you can for example export your ball class to action script:
Library>RMB on your symbol>Properties>ActionScript Linkage>Export for ActionScript
Type your class name under Class: field like "MyBallClass" and hit OK.
Now you can construct this ball in your code and replace old one like this:
var newBall:MyBallClass = new MyBallClass();
addChild(newBall);
newBall.x = gameBall.x; newBall.y = gameBall.y;
gameBall = newBall;
Additionally you can define new variable like var speedModifier:Number = 1; to use with:
gameBall.x += bSpeedX * speedModifier;
gameBall.y += bSpeedY * speedModifier;
And change that also when you change the ball.
If You want to have multiple balls at same time You really should consider build this in OOP. For simplest example in addition to previous one
You can create MyBallClass.as file and write in it something like:
package
{
import flash.display.Sprite;
import flash.geom.Point;
public class MyBallClass extends Sprite
{
public var speedFactor:Number;
public var speed:Point = new Point(-3.5, -2.5);
public function MyBallClass(x:Number, y:Number, speedFactor:Number = 1)
{
this.x = x; this.y = y;
this.speed = speed;
}
}
}
Now you can create container for all the balls in yor game.
var balls:Vector<MyBallClass> = Vector<MyBallClass>([]);
and run your physics for all of them in a loop.
Generally main code would look something like this:
var balls:Vector.<MyBallClass> = Vector.<MyBallClass>([]);
addBall(...)//place first ball.
function loop(e:Event):void {
processBalls();
if(wantToAddNewSuperSpeedBall) addBall(x,y,3);
...
}
function processBalls() {
for (var i:int = 0; i < balls.length; i++) {
detecCollision(balls[i]);
moveBall(balls[i]);
//any code that process a single ball...
}
}
function addBall(x:Number, y:Number, speedFactor:Number = 1) {
var newBall:MyBallClass = new MyBallClass(x,y, speedFactor);
addChild(newBall);
balls.push(newBall);
}
function moveBall(ball:MyBallClass) {
ball.x += ball.speed.x * ball.speedFactor;
ball.y += ball.speed.y * ball.speedFactor;
}
So you should modify all functions which affect ball behavior to work with ball passed as argument, not only one specific instance and then use them for all balls.
There are more to cover in this topic and this isn't maybe the best approach but I've tried to make it easy to understend. There a lot of guides for OOP so you can get better idea about what is going on if you read them.
I hope that helped you somehow.

AS3 best performance for side scrolling games (scroll lagging)

Is there anyone who can point me in any direction what causes the lagging in a very simple side scrolling engine?
Example here: http://grtest.hu/sidescroll/sidescroll.html
Source: http://grtest.hu/sidescroll/sidescroll.zip
Is this a frame buffer problem or something else? i really don't understand... it's so simple.
Or should i use gaming engines like Box2D, FlashPunk?
The code is:
import flash.events.Event
bg.addEventListener(Event.ENTER_FRAME,moveBG)
function moveBG(e:Event){
e.currentTarget.y <= -500 ? e.currentTarget.y = 0 : e.currentTarget.y -=3
}
here a simple code exemple for geting the frame time and move your bg using it:
var lastTime :Number = 0; // keep the last frame time
var moveSpeed :Number = 3 * 60; // 3 pixels by frame at 60 fps
bg.addEventListener( Event.ENTER_FRAME, onEnterFrame );
bg.cacheAsBitmap = true;
function onEnterFrame( e:Event )
{
var now :Number = getTimer() / 1000; // get time in seconds
var frameTime :Number = now - lastTime; // calculate frame time using the last time and the actual time
lastTime = now; // saving the last time
bg.y -= moveSpeed * frameTime;
if( bg.y <= -500 ) bg.y = 0;
}

AS3 Missile Logic

I want to create a simple missile object, which moves at a set speed and rotates towards a specific target at a given rotation speed. However, I'm having trouble figuring out the math of it. This is my code so far:
private function enterFrame(e:Event):void {
// Rotate the missile towards the target.
var targetAngle:Number = getAngle(target.x, target.y, x, y);
if (targetAngle < 0) {
targetAngle += 360;
}
if (targetAngle - turnSpeed > rotation) {
rotation += turnSpeed;
} else if (targetAngle + turnSpeed < rotation) {
rotation -= turnSpeed;
} else {
rotation = targetAngle;
}
// Set the target point to move to based on angle and speed.
var newX:Number = x + Math.sin(degreesToRadians(rotation)) * speed;
var newY:Number = y + Math.cos(degreesToRadians(rotation)) * speed;
// Move to new location
x = newX;
y = newY;
}
private function getAngle (x1:Number, y1:Number, x2:Number, y2:Number):Number {
var dx:Number = x2 - x1;
var dy:Number = y2 - y1;
return (Math.atan2(dy,dx) * 180) / Math.PI;
}
private function degreesToRadians(degrees:Number):Number {
return degrees * Math.PI / 180;
}
I've been trying to debug it using trace and such, but I can't seem to figure out where the problem is, most likely because there are many problems and I can't tell if I've fixed one because the others are masking it. I suspect that the issue(s) lie somewhere in the rotation calculations, since I'm pretty sure that the movement part is working as it should, but I can't say for sure.
At any rate, whatever I do, the missiles always seem to fly off in random directions, sometimes tracking towards straight up, or straight down, or just looping around after nothing in particular.

Movement in AS3

I am learning AS3. How can I move a symbol?
My Code
var counter:int = new int();
counter = 0;
var point:symbol1 = new symbol1();
addChild(point);
point.x = 25 + 50;
point.y = 25 + 50;
stage.addEventListener(KeyboardEvent.KEY_DOWN, move_handler);
function move_handler(e) {
if (e.keyCode == Keyboard.SPACE) {
while (counter < 200)
{
trace(counter);
point.x += 1;
counter += 1;
}
}
}
But when I press space the symbol is to fast. How can edit the speed of the point?
You need to use an ENTER_FRAME event :
stage.addEventListener(Event.ENTER_FRAME,stageEnterFrame);
function stageEnterFrame(e:Event):void{
displayObject.x+=1
}
The displayList is updated only after code execution, that's why your object move so 'fast'.
This link may help you understand the process.
At the moment you are waiting for the user to press the space bar and then moving the symbol to the right by one pixel 200 times.
But as OXMO456 has said all 200 times that it moves to the right happen at the same time as if you had manually typed "point.x += 1;" 200 times.
if your intention is to only let it move to the right 200 times then you could replace the while statement with an if statement:
if(counter<200){
trace(counter);
point.x+=1;
counter+=1;
}
You could then change the speed it moves at by changing the number after "point.x+=".
An even better way of changing the speed would be by using a variable to make it clearer what the number does. This also makes it easier to use that number for other things, like moving in other directions at the same speed.
Here's what the finished code would look like with these changes and a bit of clean up:
var counter:int = 0; // setting this variable as you define it saves space
var speed:Number = 1; // here's the speed variable (declared as a number so you can have fractions)
var point:symbol1 = new symbol1();
addChild(point);
point.x = 75; // 25+50 is 75, one less thing for flash to work out
point.y = 75;
stage.addEventListener(KeyboardEvent.KEY_DOWN, move_handler);
function move_handler(e) {
if (e.keyCode == Keyboard.SPACE) {
if (counter < 200)
{
trace(counter);
point.x += 1;
counter += 1;
}
}
}
Does that make sense?
Do it like this:
Point.x += 0.2; instead of point.x += 1;
this event type is what you want:
' stage.addEventListener(Event.ENTER_FRAME,enterFrameHandler)'
Use tween:
import libraries:
import fl.transitions.Tween;
import fl.transitions.easing.*;
import fl.transitions.TweenEvent;
var myTween:Tween = new Tween(ball, "x", Strong.easeOut, ball.x, ball.x + 100, 5, true);
This code moving your object ("ball") to 100 on "x" axis in 5s.
Your while loop is making it fast, if you remove your while statement then it will work on SPACE DOWN
Welcome to the world of AS3.
Your description of your problem is a little vague, but i think i know what you what to do. You want to tween a display object (symbol1) 200 px right everytime you hit space? if so, here is how you do it:
import flash.events.KeyboardEvent;
import flash.events.Event;
var destinationX:int = 0; // this contains the point's destination x
var point:symbol1 = new symbol1(); // best practice is to name all your classes starting with upper case, like Symbol1, not symbol1
addChild(point);
point.x = 25 + 50;
point.y = 25 + 50;
stage.addEventListener(KeyboardEvent.KEY_DOWN, move_handler);
stage.addEventListener(Event.ENTER_FRAME, render);// run render function every frame
function move_handler(e:KeyboardEvent):void{// another best practice, when injecting a variable into a function declare what type the variable is, in this case e is a KeyboardEvent. :void when not returning any values from the function, basically all functions you make in the beginning should look like this
if (e.keyCode == Keyboard.SPACE) {
destinationX += 200;// add 200 to destinationX
}
}
function render(e:Event):void{ // runs every frame, if you set your fps to 30, then this will run 30 times a second
if(destinationX > point.x){//Check if point's destination x is more than the points current x position
point.x += 1;// add 1 to points x. you can change this if you want it to go faster
}
}
Check out the Greensock library - it will take all the onEnterFrame complexity out for you and has some great features.
Full doc and examples at http://www.greensock.com/
You need this
var counter:int = new int();
var vel = 1; //<------- Move 1 pixel by frame
counter = 0;
var point:symbol1 = new symbol1();
addChild(point);
point.x = 25 + 50;
point.y = 25 + 50;
stage.addEventListener(KeyboardEvent.KEY_DOWN, move_handler);
function move_handler(e) {
if (e.keyCode == Keyboard.SPACE) {
stage.addEventListener(Event.ENTER_FRAME,moveEnterFrame);
stage.removeEventListener(KeyboardEvent.KEY_DOWN, move_handler);
}
}
function moveEnterFrame(e:Event):void{
point.x += vel;
counter ++;
if(counter >= 200){
stage.removeEventListener(Event.ENTER_FRAME,moveEnterFrame);
counter = 0;
stage.addEventListener(KeyboardEvent.KEY_DOWN, move_handler);
}
}
ENTER_FRAME is the same of While.
stage.addEventListener(Event.ENTER_FRAME, nameFunction); //this event execute fps ones on default 24 frames for seconds
var speed:int = 5;
function nameFunction(ev:Event){
simbol.x += speed;
}
Draw anything and name it in the instance name box ..... so this well speed up and down by the space key ...... i use the frame rate
import flash.events.KeyboardEvent;
import flash.ui.Keyboard;
stage.addEventListener(Event.ENTER_FRAME,stageEnterFrame);
var fremCount:int;
var upDown:int;
function stageEnterFrame(e:Event):void{
if(fremCount<30 && upDown==0){
box.x+=1
fremCount++
}
if(fremCount==30){
upDown=1;
trace("For next : "+fremCount , upDown);
}
if(upDown==1){
box.x-=1
fremCount--;
}
if(upDown==1 && fremCount==0){
upDown=0;
}
}
stage.addEventListener(KeyboardEvent.KEY_DOWN, myKeyDown);
function myKeyDown(e:KeyboardEvent):void{
if (e.keyCode == Keyboard.SPACE){
trace("Success!"+stage.frameRate);
stage.frameRate += 5;
if (stage.frameRate>150){stage.frameRate=0;}
}
}
import flash.events.Event;
var point:MovieClip = new Symbol1();
addChild(point);
point.x = 25 + 50;
point.y = 25 + 50;
stage.addEventListener(KeyboardEvent.KEY_DOWN, move_handler);
function move_handler(e)
{
if (e.keyCode == Keyboard.SPACE)
{
stage.addEventListener(Event.ENTER_FRAME, moveRight);
}
}
function moveRight(evt:Event):void
{
point.x+=1;
}
I think this is exactly what you need. Firtly you create and call upon the key_down function. Inside this function you want to call for the move function itself. This is the function I created at the bottom. To make it stop at for example 200px I suggest to work with an if-statement and a removeEventlistener.
Please note that I changed some small codings eg "var point:MovieClip = new Symbol1(); " to make it appropriate for my symbol.
why not declare your counter variable as Number (not as int)
var counter:Number = new Number();
then change your statment as
point.x += 0.1;
counter += 0.1;
this will slow down your Point movieclip. you can change motion by changing 0.1 to any value you want.
The reason why your symbol is too fast is that your while loop iterates your point.x value 200 times in only one loop. To limit your symbol position, you must use an if statement instead of a while loop:
var point:symbol1 = new symbol1();
point.x = 75; // 25 + 50;
point.y = 75; // 25 + 50;
addChild(point);
const SPEED:Number = 0.7;
const DX:int = 200; // distance to cover
var counter:Number = 0; // counts the distance covered
stage.addEventListener(KeyboardEvent.KEY_DOWN, move_handler);
function move_handler(e:KeyboardEvent):void
{
if (e.keyCode == Keyboard.SPACE && counter < DX)
{
point.x += SPEED;
counter += SPEED;
trace(counter); // stops at 200
}
}
Use the Enter Frame method.
Please don't hardcode as well :P
If you are starting you may want to consider giving one of the many existing tween engines in order to get smooth results quickly.