How do i detect collision and stack falling objects in as3 flash? - actionscript-3

I have a little problem when I'm trying to get the sqares to stack, almost like in tetris.
I don't know how I can controll the different squares so i can check for collision. I have made one square with as3 linkage name Square.
var timer:Timer = new Timer(12);
timer.addEventListener(TimerEvent.TIMER, doStuff);
timer.start();
var newSquare= new Square();
nyFirkant.y = 0;
nyFirkant.x = Math.floor( Math.random() * 4) * 100;
addChild(newSquare);
stage.addEventListener(KeyboardEvent.KEY_DOWN, tastLytter);
function keyListener(evt:KeyboardEvent)
{
var key:int = evt.keyCode;
if (key== Keyboard.RIGHT && newSquare.x < 400)
{
newSquare.x += 100;
}
if (key== Keyboard.LEFT && newSquare.x > 0)
{
newSquare.x -= 100;
}
}
function doStuff(evt:TimerEvent)
{
if (newSquare.y <= 400 - newSquare.height)
{
newSquare.y = newSquare.y + 2;
}
if (newSquare.y == 350)
{
newSquare= new Square();
newSquare.y = 0;
newSquare.x = Math.floor( Math.random() * 4) * 100;;
addChild(newSquare);
}
}

Use hitTestObject, it's a method in the MovieClip class.
if (firstBlock.hitTestObject(secondBlock)) {
trace("This block hit the other block");
//Do stuff
}
Obviously this isn't a "drop-in" solution - you'd be much better off using a physics engine such as Box2D, but hitTestObject should do fine for your purposes.

Related

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.

AS3 No keyboard input registering

so I want an object to orbit around another, but I want it to do it only when the right arrow key is pressed. When I run this program, the orbiter doesn't move at all, even when the right arrow key is pressed and it doesn't trace!
Any help is greatly appreciated!
PS Do I have to use an event listener with KEY_DOWN or can I return a number and check it?
var orbiter:Orbiter = new Orbiter();
var origin:Origin = new Origin();
var angle:Number = 0;
var speed:Number = 1.5;
var radius:Number = 75;
origin.x= 100;
origin.y =100;
addChild(orbiter);
addChild(origin);
stage.addEventListener(Event.ENTER_FRAME, Orbit_Brah);
function Orbit_Brah(event:Event):void
{
var nLeftOrRight = CheckKeyDown;
if (nLeftOrRight == 1)
{
angle += speed;
var rad:Number = angle * (Math.PI / 180);
orbiter.x = origin.x + radius * Math.cos(rad);
orbiter.y = origin.y + radius * Math.sin(rad);
orbiter.rotation = (Math.atan2(orbiter.y-origin.y, orbiter.x-origin.x) * 180 / Math.PI);
}
}
function CheckKeyDown(event:KeyboardEvent):int
{
if (event.keyCode == Keyboard.RIGHT)
{
trace ("Key Press Registered");
return 1;
}
return 0;
}
You will need to add a listener to fetch the info from the KeyboardEvents. Store the info in a variable and use it in your update loop. You may also want to use KeyboardEvent.KEY_UP to check when the keys are released as well. Something like this.
stage.addEventListener(Event.ENTER_FRAME, Update);
stage.addEventListener(KeyboardEvent.KEY_DOWN, OnKeyboardDownHandler);
stage.addEventListener(KeyboardEvent.KEY_UP, OnKeyboardUpHandler);
function Update(pEvent : Event) : void
{
// update code here using stored info
if(_isMovingRight)
{
//
}
}
function OnKeyboardDownHandler(pEvent : KeyboardEvent) : void
{
switch(pEvent.keyCode)
{
case Keyboard.RIGHT:
_isMovingRight = true;
break;
}
}
function OnKeyboardUpHandler(pEvent : KeyboardEvent) : void
{
switch(pEvent.keyCode)
{
case Keyboard.RIGHT:
_isMovingRight = false;
break;
}
}
You're trying too hard. All you need to do after your declarations is:
stage.addEventListener(KeyboardEvent.KEY_DOWN, Orbit_Brah);
function Orbit_Brah(e)
{
if (e.keyCode == Keyboard.RIGHT)
{
angle += speed;
var rad:Number = angle * (Math.PI / 180);
orbiter.x = origin.x + radius * Math.cos(rad);
orbiter.y = origin.y + radius * Math.sin(rad);
orbiter.rotation = (Math.atan2(orbiter.y-origin.y, orbiter.x-origin.x) * 180 / Math.PI);
}
}
That still leaves you with one little math problem, which will be obvious when you run the code, but you can take care of that.

AS3 indexof array object property

I'm trying to complete background in kind of Space Invaders game. I want to generate stars at a random location, scroll them to the bottom of the stage and then add new star after each one is gone. I guess that the problem lies on the indexOf method, which I tried to use to find star y proprety.
I know this may be a stupid mistake, i'm a beginner :)
My current main class:
public class Main extends Sprite
{
private var ship:Ship = new Ship();
private var numStars:int = 80;
private var starArray:Array = new Array();
public function Main():void
{
stage.addChild(ship);
ship.x = stage.stageWidth / 2 - ship.width / 2;
ship.y = stage.stageHeight / 2 - ship.height / 2;
stage.addEventListener(KeyboardEvent.KEY_DOWN, keyDownHandler);
stage.addEventListener(KeyboardEvent.KEY_UP, keyUpHandler);
stage.addEventListener(Event.ENTER_FRAME, enterFrameHandler);
for (var i:int = 0; i < numStars; i++)
{
createStar();
}
}
public function createStar():void
{
var newStar:Star = new Star();
starArray.push(newStar);
stage.addChildAt(newStar,1);
newStar.x = Math.random() * stage.stageWidth;
newStar.y = Math.random() * stage.stageHeight;
newStar.alpha = Math.random();
newStar.rotation = Math.random()*360;
newStar.scaleX = Math.random();
newStar.scaleY = Math.random();
}
public function keyDownHandler(e:KeyboardEvent):void
{
if (e.keyCode == Keyboard.UP)
{
ship.accelerationY = -0.3;
}
if (e.keyCode == Keyboard.DOWN)
{
ship.accelerationY = 0.3;
}
if (e.keyCode == Keyboard.LEFT)
{
ship.accelerationX = -0.3;
}
if (e.keyCode == Keyboard.RIGHT)
{
ship.accelerationX = 0.3;
}
}
public function keyUpHandler(e:KeyboardEvent):void
{
if (e.keyCode == Keyboard.UP || e.keyCode == Keyboard.DOWN)
{
ship.accelerationX = 0;
ship.accelerationY = 0;
}
if (e.keyCode == Keyboard.LEFT || e.keyCode == Keyboard.RIGHT)
{
ship.accelerationY = 0;
ship.accelerationX = 0;
}
}
public function enterFrameHandler(e:Event):void
{
//acceleration
ship.vx += ship.accelerationX;
ship.vy += ship.accelerationY;
//friction
ship.vx *= ship.friction;
ship.vy *= ship.friction;
if (Math.abs(ship.vx) < 0.1)
{
ship.vx = 0;
}
if (Math.abs(ship.vy) < 0.1)
{
ship.vy = 0;
}
ship.rotation = ship.vx * 2;
//set speed limit
if (ship.vx > ship.speedLimit)
{
ship.vx = ship.speedLimit;
}
if (ship.vx < -ship.speedLimit)
{
ship.vx = -ship.speedLimit;
}
if (ship.vy > ship.speedLimit)
{
ship.vy = ship.speedLimit;
}
if (ship.vy < -ship.speedLimit)
{
ship.vy = -ship.speedLimit;
}
//set stage boundaries
if (ship.x < 0)
{
ship.x = 0;
}
if (ship.y < 0)
{
ship.y = 0;
}
if (ship.x + ship.width > stage.stageWidth)
{
ship.x = stage.stageWidth - ship.width;
}
if (ship.y + ship.height > stage.stageHeight)
{
ship.y = stage.stageHeight - ship.height;
}
ship.x += ship.vx;
ship.y += ship.vy;
//star enter frame code
for (var i:int = 0; i < numStars; i++)
{
starArray[i].y += 0.5 + Math.random() * 2;
}
if (starArray.indexOf(starArray.y) > stage.stageHeight) //if y property of any star is higher than stage height, create a new star
{
createStar();
}
}
}
i recommend looking into tween utilities like TweenLite which do time based animations: (http://www.greensock.com/tweenlite/)
also recommend looking into object pooling, reused objects instead of creating new ones. Good thing to learn as a new programmer.
you are correct about where your issue lies
i got your program working correctly with the following change:
---------change these lines-------------
//star enter frame code
for (var i:int = 0; i < numStars; i++)
{
starArray[i].y += 0.5 + Math.random() * 2;
}
if (starArray.indexOf(starArray.y) > stage.stageHeight) //if y property of any star is higher than stage height, create a new star
{
createStar();
}
---------to this-------------
//star enter frame code
for (var i:int = 0; i < numStars; i++)
{
var star:Star = starArray[i];
star.y += 0.5 + Math.random() * 2;
if (star.y>stage.stageHeight){
//dont create a new star -- memory leak
//move the same star to a new random location
star.y = 0;
}
}
Instead of just creating a new star, why not just replace it at the top outside of the screen?
As for indexOf, it only returns the index in an array of the object being passed. And in this case you're passing the y value of an array, which doesn't have that property.
Instead, move your position checking code to your for loop in the game loop. That way, you already have an index (your i variable) of the star that's outside the boundaries and if it is, just reposition it and save some memory!
for (var i:int = 0; i < numStars; i++)
{
starArray[i].y += 0.5 + Math.random() * 2;
if(starArray[i].y > stage.stageHeight)
{
// Repositions the star between x: 0 to stageWidth, y: -5 to -15
starArray[i].y = Math.random() * -10 - 5;
starArray[i].x = Math.random() * stage.stageWidth;
}
}

Objects to bounce around the screen?

I would like to make the 5 'burger' objects bounce around the screen so they are harder to shoot as is the aim of my game. But, so far they are only lining up at the top of the stage so it's way too easy to play. Would I need to create 5 separate objects with 5 separate instance names etc.
This is what I have so far:
var firing:Boolean = false;
var bullet:Bullet1 = new Bullet1();
stage.addEventListener(KeyboardEvent.KEY_DOWN, keydown);
function keydown(event:KeyboardEvent):void {
switch(event.keyCode) {
case Keyboard.LEFT :
ball.x -= 10;
break;
case Keyboard.SPACE :
if (!firing) {
fire();
}
break;
case Keyboard.RIGHT :
ball.x += 10;
break;
case Keyboard.UP :
ball.y -= 10;
break;
case Keyboard.DOWN :
ball.y += 10;
break;
default :
break;
}
}
stage.addEventListener(KeyboardEvent.KEY_DOWN, keydown);
function fire() {
addChild(bullet);
firing = true;
bullet.x = ball.x;
bullet.y = ball.y - 60
;
}
addEventListener(Event.ENTER_FRAME, movestuff);
function movestuff(event:Event):void {
if (firing) {
bullet.y -= 20;
if (bullet.y < 0) {
firing = false;
removeChild(bullet);
}
}
}
var numBurger:Number = 5;
var array:Array = new Array();
for (var i:uint = 0; i<numBurger; i++) {
var burger:Burger = new Burger();
array.push(burger);
addChild(burger);
burger.x = 100 + 100*i;
burger.y = 50;
}
addEventListener(Event.ENTER_FRAME, checkCollision);
function checkCollision(event:Event)
{
for (var i:uint=0; i<array.length; i++)
{
if (array[i].hitTestObject(bullet))
{
removeChild(array[i]);
array.splice(i,1);
return;
}
}
}
Thanks for any help.
No, you would not have to create each movie clip separately if you use a loop to create randomized x and y locations for each burger. You can also use Math.random() to give a random speed and direction to each burger. In the code below these values are held in "direction_ary" array. This code creates five MovieClips of the "Burger"class, and places them at random points on the screen. The code also creates random speeds and directions for each MovieClip:
import flash.events.Event;
function find_random(max,min){
return Math.round(min+(max-min)*Math.random());
}
var ary:Array = [];
var direction_ary:Array = [];
for(var i:uint=0;i<5;i++){
ary[i]=new Burger();
ary[i].name="burger"+(i);
ary[i].x=find_random(stage.stageWidth-ary[i].width,ary[i].width);
ary[i].y=find_random(stage.stageHeight-ary[i].height,ary[i].height);
addChild(ary[i]);
direction_ary[i]=[find_random(5,-5),find_random(5,-5)];
for(var e:uint=0;e<100;e++){
if(direction_ary[i][0]==0||direction_ary[i][1]==0){
direction_ary[i]=[find_random(5,-5),find_random(5,-5)];
}else{
break;
}
}
}
stage.addEventListener(Event.ENTER_FRAME,update_burgers);
function update_burgers(e:Event){
for(var i:uint=0;i<5;i++){
if (ary[i].x>stage.stageWidth||ary[i].x<0){
direction_ary[i][0]*=-1;
}
if (ary[i].y>stage.stageHeight||ary[i].y<0){
direction_ary[i][1]*=-1;
}
ary[i].x+=direction_ary[i][0];
ary[i].y+=direction_ary[i][1];
}
}
The code is fairly self explanatory. Good luck with your project.
Cheers,
Drake Swartzy

Level progression in a platform game? (Actionscript 3)

I've been working on a Platformer for a couple of weeks now and i can't seem to get the level progression working. I'm using a basic hitTest on a box to signal the movement from frame 1(level 1) to frame 2 (level 2) but once the character hits the exit box, i get the following error
TypeError: Error #1009: Cannot access a property or method of a null object reference.
at LevelProg_fla::MainTimeline/loop()
What can i do so that it moves to the next frame(level)? If it helps, my code is in a frame rather than a class. Basically, the only code that i'm using for level progression is
if (player.hitTestObject(exit))
{
gotoAndPlay("levelTwo");
}
with "levelTwo" being the name of the next frame (next level). The rest of the game's code is as follows (pardon the messyness of it, I've been more focused on getting the darn thing to work :b)
import flash.events.KeyboardEvent;
import flash.events.Event;
//some variables to track the player's speed
var speedX = 0;
var speedY = 0;
player.height = 80.0;
player.width = 60.0;
//loop through all the platform objects to generate the level
var level:Array = new Array();
for (var i=0; i<numChildren; i++)
{
if (getChildAt(i) is platform)
{
level.push(getChildAt(i).getRect(this));
}
}
//make variables to store key states
var kUp = false;
var kDown = false;
var kLeft = false;
var kRight = false;
//listen for key presses and releases
stage.addEventListener(KeyboardEvent.KEY_DOWN, kD);
stage.addEventListener(KeyboardEvent.KEY_UP, kU);
function kD(k:KeyboardEvent)
{
if (k.keyCode==37) kLeft=true;
if (k.keyCode==38) kUp=true;
if (k.keyCode==39) kRight=true;
if (k.keyCode==40) kDown=true;
}
function kU(k:KeyboardEvent)
{
if (k.keyCode==37) kLeft=false;
if (k.keyCode==38) kUp=false;
if (k.keyCode==39) kRight=false;
if (k.keyCode==40) kDown=false;
}
//Make a looping function
addEventListener(Event.ENTER_FRAME, loop);
function loop(e:Event)
{
//lateral movement checks
if (kLeft)
{
speedX=-10;
}
else if (kRight)
{
speedX=10;
}
else
{
speedX*=0.5; //friction to slow player down (kinda like mario)
}
//does not stop the character
//move player based on the above
player.x+=speedX;
//animations
if (speedX > 0)
{
trace("right pressed");
//player.gotoAndPlay("walkRight");
}
if (speedX < 0)
{
trace("left pressed");
//player.gotoAndPlay("walkLeft");
}
//sidewards hit tests
for (i=0; i<level.length; i++)
{
if (player.getRect(this).intersects(level[i]))
{
if (speedX > 0) ////moving right collision and stuffs
{
player.x = level[i].left-player.width/2;
}
if (speedX < 0) ////moving left collision and stuffs
{
player.x = level[i].right+player.width/2;
}
//RIGHTIO
speedX = 0 //kills the speed
}
}
//vertical checks
speedY+=1;
player.y+=speedY;
var jumpable = false
//vertical hitTests
//note that it's the same as the x code but just changed like 5 things.
for (i=0; i<level.length; i++)
{
if (player.getRect(this).intersects(level[i]))
{
if (speedY > 0) ////moving down collision and stuffs
{
player.y = level[i].top-player.height/2;
speedY=0;
jumpable = true;
}
if (speedY < 0) ////moving up collision and stuffs
{
player.y = level[i].bottom+player.height/2;
speedY*=-0.5; //bounces off cielings
}
//RIGHTIO
speedX = 0 //kills the speed
}
}
//jumps if possible
if (kUp && jumpable)
{
speedY=-15;
}
//gravity might help}
//move player with camera function/code/script/tired
this.x=-player.x+(stage.stageWidth/2); //centers the player
this.y=-player.y+(stage.stageWidth/2); //centers the player
//Progresses the player to level 2
if (player.hitTestObject(exit))
{
gotoAndPlay("levelTwo");
}
}