Collision and movements not working as expected - actionscript-3

I am trying to do an example of collision in Action Script 3. It's a character that should stop when it hits a platform. It works well when I move only to the right, left, up or down directions, but if I try to move in the diagonals, if the characteris colliding with the platform, the object goes to a different area of the screen.
This is the compiled example: http://dl.dropbox.com/u/5282142/GameDemo.html
And below is my code.
Now, does anyone know a better way to do what I am doing, or how can I get the character not to go to a weird position when I try to move it in a diagonal?
var level:Array = new Array();
for (var i = 0; i < numChildren; i++) {
if (getChildAt(i) is Platform) {
level.push(getChildAt(i).getBounds(this));
}
}
var speedX:int = 0;
var speedY:int = 0;
var kLeft:Boolean = false;
var kRight:Boolean = false;
var kDown:Boolean = false;
var kUp:Boolean = false;
stage.addEventListener(KeyboardEvent.KEY_DOWN, onKeyDownHandler);
stage.addEventListener(KeyboardEvent.KEY_UP, onKeyUpHandler);
function onKeyDownHandler(event:KeyboardEvent):void {
if (event.keyCode == 37) kLeft = true;
if (event.keyCode == 38) kUp = true;
if (event.keyCode == 39) kRight = true;
if (event.keyCode == 40) kDown = true;
}
function onKeyUpHandler(event:KeyboardEvent):void {
if (event.keyCode == 37) kLeft = false;
if (event.keyCode == 38) kUp = false;
if (event.keyCode == 39) kRight = false;
if (event.keyCode == 40) kDown = false;
}
addEventListener(Event.ENTER_FRAME, loop);
function loop(event:Event):void {
moveChar();
bound();
}
function moveChar():void {
if (kLeft) {
speedX = -10;
} else if (kRight) {
speedX = 10;
} else {
speedX *= 0.5;
}
if (kUp) {
speedY = -10;
} else if (kDown) {
speedY = 10;
} else {
speedY *= 0.5;
}
character.x += speedX;
character.y += speedY;
}
function bound():void {
if (character.x > (800 - character.width/2)){
character.x = 800 - character.width/2;
}
if (character.x < (character.width/2)){
character.x = character.width/2;
}
if (character.y > (480 - character.height/2)){
character.y = 480 - character.height/2;
}
if (character.y < (character.height/2)){
character.y = character.height/2;
}
for (i = 0; i < level.length; i++) {
if (character.getBounds(this).intersects(level[i])) {
if (speedX > 0) {
character.x = level[i].left - character.width/2;
}
if (speedX < 0) {
character.x = level[i].right + character.width/2;
}
}
}
for (i = 0; i < level.length; i++) {
if (character.getBounds(this).intersects(level[i])) {
if (speedY > 0) {
character.y = level[i].top - character.height/2;
}
if (speedY < 0) {
character.y = level[i].bottom + character.height/2;
}
}
}
}

Your Problem lies in this part of your code :
for (i = 0; i < level.length; i++) {
if (character.getBounds(this).intersects(level[i])) {
if (speedX > 0) {
character.x = level[i].left - character.width/2;
}
if (speedX < 0) {
character.x = level[i].right + character.width/2;
}
}
}
for (i = 0; i < level.length; i++) {
if (character.getBounds(this).intersects(level[i])) {
if (speedY > 0) {
character.y = level[i].top - character.height/2;
}
if (speedY < 0) {
character.y = level[i].bottom + character.height/2;
}
}
}
The character does not actually move to a random position. It is being set by you, above.
You have to create a better logic (as per the scenario) where your code should not get confused when two keys are down simultaneously & a collision occurs.

Related

Actionscript 3 error 1009: Cannot access a property or method of a null object reference

I'm trying to make a simple game on Animate CC. Everything seems to work fine except when I look in the output, I get the following error:
TypeError: Error #1009: Cannot access a property or method of a null
object reference.
at _2D_CW2_Game_v10_8_fla::MainTimeline/move()
at _2D_CW2_Game_v10_8_fla::MainTimeline/updateOb()
So I know where the issue might be, and I've been trying tweaking the code for days, googling possible solutions, but to no avail...
My entire source code is as below. Any feedback/suggestions will be greatly appreciated.
import flash.ui.Keyboard;
import flash.events.KeyboardEvent;
import flash.events.MouseEvent;
import flash.events.Event;
import flash.display.MovieClip;
import flash.net.URLRequest;
import flash.media.Sound;
import flash.media.SoundMixer;
//==================================================
// Variable declaration
//==================================================
// defines the variables for boundaries
var left:Number = 0;
var top:Number = 0;
var right:Number = stage.stageWidth;
var bottom:Number = stage.stageHeight;
var velX:Number = 0;
var velY:Number = 0;
var gravity:Number = 1;
var friction:Number = 0.8;
var bounce:Number = -0.5;
var score:Number = 2;
var cv:Number = 0;
var curCount:Number = 30; // countdown 30s
var rightKeyDown:Boolean = false;
var leftKeyDown:Boolean = false;
var upKeyDown:Boolean = false;
var touchGround:Boolean = false;
// create and place player object on stage
var player:Player = new Player();
player.x = 110;
player.y = 460;
addChild(player);
// create obstacle array
var obstacles:Array = new Array();
var numOb:Number = 3;
// create and place enemies on stage
for (var i:Number = 0; i < numOb; i++) {
var ob:Npc = new Npc();
ob.x = 800;
ob.y = 470;
ob.scaleX = -1;
ob.vx = Math.random() * 20 + 1;
addChild(ob);
obstacles.push(ob);
}
//==================================================
// Event handlers
//==================================================
stage.addEventListener(Event.ENTER_FRAME, EntFrame);
addEventListener(Event.ENTER_FRAME, updateOb);
stage.addEventListener(KeyboardEvent.KEY_DOWN, keyDown);
stage.addEventListener(KeyboardEvent.KEY_UP, keyUp);
//==================================================
// Functions
//==================================================
function keyDown(e:KeyboardEvent):void {
if (e.keyCode == Keyboard.RIGHT) {
rightKeyDown = true;
}
if (e.keyCode == Keyboard.LEFT) {
leftKeyDown = true;
}
if (e.keyCode == Keyboard.UP) {
// if player isn't already jumping and is on the ground
if (!upKeyDown && touchGround) {
// then start jumping
isJumping();
}
upKeyDown = true;
}
}
function keyUp(e:KeyboardEvent):void {
if (e.keyCode == Keyboard.RIGHT) {
rightKeyDown = false;
}
if (e.keyCode == Keyboard.LEFT) {
leftKeyDown = false;
}
if (e.keyCode == Keyboard.UP) {
upKeyDown = false;
}
}
function EntFrame(e:Event):void {
player.x += velX;
player.y += velY;
velX *= friction;
velY += gravity;
if (player.y >= 450) {
touchGround = true;
player.y = 450;
}
// boundary checks
if (player.x + player.width/2 > right) {
player.x = right - player.width/2;
player.velX *= bounce;
} else if (player.x - player.width/2 < left) {
player.x = left + player.width/2;
player.velX *= bounce;
}
// make player move left or right
controls();
if (curCount > 0) {
cv++;
if (cv >= 30) {
curCount--;
cv = 0;
timertext.text = String(curCount);
if (curCount == 0) {
restart();
gotoAndStop("gameOverWon");
}
}
}
}
function updateOb(e:Event):void {
// make obstacles move
for (var i:Number = 0; i < numOb; i++) {
var ob:Npc = obstacles[i];
move(ob);
if (player.hitTestObject(obstacles[i])) {
/*if (obstacles[i].hitTestPoint(player.x + player.width/2, player.y + player.height/2, true)
|| obstacles[i].hitTestPoint(player.x + player.width/2, player.y - player.height/2, true)
|| obstacles[i].hitTestPoint(player.x - player.width/2, player.y + player.height/2, true)
|| obstacles[i].hitTestPoint(player.x - player.width/2, player.y - player.height/2, true))*/
bumpOb(obstacles[i]);
}
}
scoretext.text = String(score);
if (score == 0) {
restart();
gotoAndStop("gameOverLost");
}
}
// applies basic velocity to enemies
function move(moveOb) {
moveOb.x -= moveOb.vx;
if (moveOb.x + moveOb.width/2 > right) {
moveOb.x = right - moveOb.width/2;
moveOb.vx *= bounce;
moveOb.scaleX = -1;
}
if (moveOb.x - moveOb.width/2 < left) {
moveOb.x = left + moveOb.width/2;
moveOb.vx *= bounce;
moveOb.scaleX = 1;
}
}
function bumpOb(p) {
if (p) {
p.removeEventListener(Event.ENTER_FRAME, updateOb);
if (p.parent) {
removeChild(p);
score--;
}
}
}
function restart() {
if(contains(player)) {
removeChild(player);
}
for (var i:int = 0; i < numOb; i++) {
if (contains(obstacles[i]) && obstacles[i] != null) {
removeChild(obstacles[i]);
obstacles[i] = null;
}
}
// returns a new array that consists of a range of elements from the original array,
// without modifying the original array
obstacles.slice(0);
}
function controls() {
if (rightKeyDown) {
velX += 3;
player.scaleX = 1;
}
if (leftKeyDown) {
velX -= 3;
player.scaleX = -1;
}
}
function isJumping() {
touchGround = false;
velY = -15;
}
//==================================================
// Sound control for background music
//==================================================
btnMute.addEventListener(MouseEvent.CLICK, mute);
function mute(e:MouseEvent):void {
SoundMixer.soundTransform = new SoundTransform(0);
btnMute.removeEventListener(MouseEvent.CLICK, mute);
btnMute.addEventListener(MouseEvent.CLICK, unmute);
}
function unmute(e:MouseEvent):void {
SoundMixer.soundTransform = new SoundTransform(1);
btnMute.removeEventListener(MouseEvent.CLICK, unmute);
btnMute.addEventListener(MouseEvent.CLICK, mute);
}
I had the same problem when I created interactive elements for animation. Check which layer the interactive object is on. A similar error occurred when the object overlapped something that was located on the layer above.
You can try...
1) Your Npc is a class/library object, right?
Give the source MC/Sprite, the instance name of moveOb or p.
2) or else try... Use function parameters (this is a better coding style):
(2a) Since you say..
var ob:Npc = obstacles[i];
move(ob);
ps: why not simplify (without var) as : move( obstacles[i] ); ...?
(2b) Your move function should specify a data type together with your parameter name...
//# applies basic velocity to enemies
//# Wrong...
//function move(moveOb) {
//# Better...
function move( moveOb : Npc ) {
//# Aso fix as...
function bumpOb(p : Npc ) {
By using function parameters, you can now give unique names to the (function's) input parameters but stay referencing the same (or compatible) data type.
Let me know how it goes.
The obstacles array may have null elements in the middle. What if you add a condition to continue if it's null?
function updateOb(e:Event):void {
// make obstacles move
for (var i:Number = 0; i < obstacles.length; i++) {
var ob:Npc = obstacles[i];
if(!ob) continue;
move(ob);
if (player.hitTestObject(ob)) {
/*if (obstacles[i].hitTestPoint(player.x + player.width/2, player.y +
player.height/2, true)
|| obstacles[i].hitTestPoint(player.x + player.width/2, player.y -
player.height/2, true)
|| obstacles[i].hitTestPoint(player.x - player.width/2, player.y +
player.height/2, true)
|| obstacles[i].hitTestPoint(player.x - player.width/2, player.y -
player.height/2, true))*/
bumpOb(obstacles[i]);
}
}
scoretext.text = String(score);
if (score == 0) {
restart();
gotoAndStop("gameOverLost");
}
}

AS3 Platformer Slope Detection

i am in the process of making a platformer in AS3. However, one thing im struggling with is how to manage slope detection. Preferably id like something similar to that of games like fancy pants adventures, but id really prefer not to use an external thing such as Box2D or CDK, because both of which confuse me greatly, and id generally prefer just to not have one. All my attempts have had the problem that i can get it to work with some slopes but not all (e.g character manages up one slope, but falls through the other) then when i change it to suit the other, it doesnt suit the first one (e.g player manages the second slope, but bounces up and down crazily on the second...
So, any help would be greatly appreciated...
Thanks.
Code is as follows.
//var setup
var leftPressed: Boolean = false;
var rightPressed: Boolean = false;
var upPressed: Boolean = false;
var downPressed: Boolean = false;
var leftBumping: Boolean = false;
var rightBumping: Boolean = false;
var upBumping: Boolean = false;
var downBumping: Boolean = false;
var lowerleftBumping: Boolean = false;
var lowerrightBumping: Boolean = false;
var leftBumpPoint: Point = new Point(-30, -87);
var rightBumpPoint: Point = new Point(30, -87);
var lowerleftBumpPoint: Point = new Point(-32, -2);
var lowerrightBumpPoint: Point = new Point(32, -2);
var upBumpPoint: Point = new Point(0, -174);
var downBumpPoint: Point = new Point(0, 0);
var scrollX: Number = -4;
var scrollY: Number = -68;
var ySpeed: Number = 0;
var xSpeed: Number = 0;
var speedConstant: int = 5;
var maxSpeedConstant: Number = 30;
var frictionConstant: Number = 0.9;
var gravityConstant: Number = 2;
var jumpConstant: Number = -45;
//game
stage.addEventListener(KeyboardEvent.KEY_DOWN, keyDownHandler);
stage.addEventListener(KeyboardEvent.KEY_UP, keyUpHandler);
stage.addEventListener(Event.ENTER_FRAME, loop);
function keyDownHandler(e: KeyboardEvent): void {
if (e.keyCode == Keyboard.LEFT) {
leftPressed = true;
} else if (e.keyCode == Keyboard.RIGHT) {
rightPressed = true;
} else if (e.keyCode == Keyboard.UP) {
upPressed = true;
} else if (e.keyCode == Keyboard.DOWN) {
downPressed = true;
}
}
function keyUpHandler(e: KeyboardEvent): void {
if (e.keyCode == Keyboard.LEFT) {
leftPressed = false;
} else if (e.keyCode == Keyboard.RIGHT) {
rightPressed = false;
} else if (e.keyCode == Keyboard.UP) {
upPressed = false;
} else if (e.keyCode == Keyboard.DOWN) {
downPressed = false;
}
}
function loop(e: Event): void {
if (back.hitTestPoint(player.x + leftBumpPoint.x, player.y + leftBumpPoint.y, true)) {
trace("leftBumping");
leftBumping = true;
} else {
leftBumping = false;
}
if (back.hitTestPoint(player.x + rightBumpPoint.x, player.y + rightBumpPoint.y, true)) {
trace("rightBumping");
rightBumping = true;
} else {
rightBumping = false;
}
if (back.hitTestPoint(player.x + upBumpPoint.x, player.y + upBumpPoint.y, true)) {
trace("upBumping");
upBumping = true;
} else {
upBumping = false;
}
if (back.hitTestPoint(player.x + downBumpPoint.x, player.y + downBumpPoint.y, true)) {
trace("downBumping");
downBumping = true;
} else {
downBumping = false;
}
if (back.hitTestPoint(player.x + lowerleftBumpPoint.x, player.y + lowerleftBumpPoint.y, true)) {
trace("lowerrightBumping");
lowerleftBumping = true;
} else {
lowerleftBumping = false;
}
if (back.hitTestPoint(player.x + lowerrightBumpPoint.x, player.y + lowerrightBumpPoint.y, true)) {
trace("lowerrightBumping");
lowerrightBumping = true;
} else {
lowerrightBumping = false;
}
if (leftPressed) {
xSpeed -= speedConstant;
} else if (rightPressed) {
xSpeed += speedConstant;
}
if (leftBumping) {
if (xSpeed < 0) {
xSpeed *= -0.5;
}
}
if (rightBumping) {
if (xSpeed > 0) {
xSpeed *= -0.5;
}
}
if (upBumping) {
if (ySpeed < 0) {
ySpeed *= -0.5;
}
}
if (downBumping) {
if (ySpeed > 0) {
ySpeed = 0; //set the y speed to zero
}
if (upPressed) {
ySpeed = jumpConstant;
}
} else {
ySpeed += gravityConstant;
}
if (xSpeed > maxSpeedConstant) { //moving right
xSpeed = maxSpeedConstant;
} else if (xSpeed < (maxSpeedConstant * -1)) { //moving left
xSpeed = (maxSpeedConstant * -1);
}
xSpeed *= frictionConstant;
ySpeed *= frictionConstant;
if (Math.abs(xSpeed) < 0.5) {
xSpeed = 0;
}
scrollX -= xSpeed;
scrollY -= ySpeed;
back.x = scrollX;
back.y = scrollY;
if (scrollY < -770) {
scrollX = -4;
scrollY = -68;
ySpeed=0
xSpeed=0
}
}
If I was forced to not use the love of my life (Box2D) then I suppose I would play around with hitTestObject and do some math on the angle of any of my slopes to generate the rate at which they would move to start. This question is a bit broad and I think the community here is more for specific problems and not architecture brainstorming.

Cannot access a property or method of a null object reference. -enterframe.Trying to get palayer out of maze

i'm making a simple game and i'm still learning as3 i want to hit test object on the stage , player with box if hittestobject gotoframe or scene all the objects are on the stage with corect instancename, maintimeline as3 below everything works fine but i get the null error.
it is a maze game.
import flash.events.KeyboardEvent;
import flash.events.Event;
import flash.geom.Rectangle;
import flash.ui.Keyboard;
var rightArrow:Boolean = false;
var leftArrow:Boolean = false;
var upArrow:Boolean = false;
var downArrow:Boolean = false;
var speed:int = 20;
stage.addEventListener(KeyboardEvent.KEY_DOWN, stage_onKeyDown);
stage.addEventListener(KeyboardEvent.KEY_UP, stage_onKeyUp);
stage.addEventListener(Event.ENTER_FRAME, stage_onEnterFrame);
function stage_onKeyDown(event:KeyboardEvent):void {
if(event.keyCode == Keyboard.RIGHT) rightArrow = true;
if(event.keyCode == Keyboard.LEFT) leftArrow = true;
if(event.keyCode == Keyboard.UP) upArrow = true;
if(event.keyCode == Keyboard.DOWN) downArrow = true;
}
function stage_onKeyUp(event:KeyboardEvent):void {
if(event.keyCode == Keyboard.RIGHT) rightArrow = false;
if(event.keyCode == Keyboard.LEFT) leftArrow = false;
if(event.keyCode == Keyboard.UP) upArrow = false;
if(event.keyCode == Keyboard.DOWN) downArrow = false;
}
function stage_onEnterFrame(event:Event):void {
var rect:Rectangle = player.getBounds(this);
var i:int = 0;
var xBump:int = 0;
var yBump:int = 0;
if(rightArrow) {
xBump = speed;
for(i = 0; i < speed; i++) {
if(maze.hitTestPoint(rect.right + i, player.y, true)) {
xBump = i - 1;
break;
}
}
}
if(player.hitTestObject(box))
{
// Go to next scene
nextFrame();
}
if(leftArrow) {
xBump = -speed;
for(i = 0; i < speed; i++) {
if(maze.hitTestPoint(rect.left - i, player.y, true)) {
xBump = -i + 1;
break;
}
}
}
if(upArrow) {
yBump = -speed;
for(i = 0; i < speed; i++) {
if(maze.hitTestPoint(player.x, rect.top - i, true)) {
yBump = -i + 1;
break;
}
}
}
if(downArrow) {
yBump = speed;
for(i = 0; i < speed; i++) {
if(maze.hitTestPoint(player.x, rect.bottom + i, true)) {
yBump = i - 1;
break;
}
}
}
player.x += xBump;
player.y += yBump;
}

addEventListener() isn't detecting KEY_UP nor KEY_DOWN

My full code is
import flash.events.KeyboardEvent;
import flash.events.Event;
//init some variables
var speedX = 0;
var speedY = 0;
msg.visible = false;
var curLevel = 2;
var level = new Array();
var flagVar;
var won = false;
//Adding level platforms
for(var i = 0; i < numChildren; i++) {
if(getChildAt(i) is platform) {
level.push(getChildAt(i).getRect(this));
}
if(getChildAt(i) is flag) { flagVar = getChildAt(i).getRect(this); }
}
//Checking key presses
var kUp = false;
var kDown = false;
var kLeft = false;
var kRight = false;
var kSpace = false;
stage.addEventListener(KeyboardEvent.KEY_DOWN, kD);
stage.addEventListener(KeyboardEvent.KEY_UP, kU);
function kD(k:KeyboardEvent) {
trace("Key down - " + k.keyCode);
if(k.keyCode == 32) { kSpace = true; }
if(k.keyCode == 37 ) { kLeft = true; }
if(k.keyCode == 38) { kUp = true; }
if(k.keyCode == 39) { kRight = true; }
}
function kU(k:KeyboardEvent) {
trace("Key up - " + k.keyCode);
if(k.keyCode == 32) { kSpace = false; }
if(k.keyCode == 37) { kLeft = false; }
if(k.keyCode == 38) { kUp = false; }
if(k.keyCode == 39) { kRight = false; }
}
addEventListener(Event.ENTER_FRAME, loopAround);
function loopAround(e:Event) {
//horizontal movement
if(kLeft) {
speedX = -10;
} else if(kRight) {
speedX = 10;
} else {
speedX *= 0.5;
}
player.x += speedX;
//horizontal collision checks
for(var i = 0; i < level.length; i++) {
if(player.getRect(this).intersects(level[i])) {
if(speedX > 0) {
player.x = level[i].left - player.width;
}
if(speedX < 0) {
player.x = level[i].right;
}
speedX = 0;
}
}
//vertical movement
speedY += 1;
player.y += speedY;
var jumpable = false;
//Vertical collision
for(i = 0; i < level.length; i++) {
if(player.getRect(this).intersects(level[i])) {
if(speedY > 0) {
player.y = level[i].top - player.height;
speedY = 0;
jumpable = true;
}
if(speedY < 0) {
player.y = level[i].bottom;
speedY *= -0.5;
}
}
}
//JUMP!
if((kUp || kSpace) && jumpable) {
speedY=-20;
}
//Moving camera and other
this.x = -player.x + (stage.stageWidth/2);
this.y = -player.y + (stage.stageHeight/2);
msg.x = player.x - (msg.width/2);
msg.y = player.y - (msg.height/2);
//Checking win
if(player.getRect(this).intersects(flagVar)) {
msg.visible = true;
won = true;
}
//Check for next level request
if(kSpace && won) {
curLevel++;
gotoAndStop(curLevel);
won = false;
}
}
The section in question is
//Checking key presses
var kUp = false;
var kDown = false;
var kLeft = false;
var kRight = false;
var kSpace = false;
stage.addEventListener(KeyboardEvent.KEY_DOWN, kD);
stage.addEventListener(KeyboardEvent.KEY_UP, kU);
function kD(k:KeyboardEvent) {
trace("Key down - " + k.keyCode);
if(k.keyCode == 32) { kSpace = true; }
if(k.keyCode == 37 ) { kLeft = true; }
if(k.keyCode == 38) { kUp = true; }
if(k.keyCode == 39) { kRight = true; }
}
function kU(k:KeyboardEvent) {
trace("Key up - " + k.keyCode);
if(k.keyCode == 32) { kSpace = false; }
if(k.keyCode == 37) { kLeft = false; }
if(k.keyCode == 38) { kUp = false; }
if(k.keyCode == 39) { kRight = false; }
}
This was working fine last night, but today I moved it to a new keyframe and now it's not working. I'm not getting any errors (even if I debug). It just won't move the character or even show up in output.
I'm still quite new to as3, so I don't really know what to do.
Thanks in advance.
Edit: After playing with it a bit, I've found out that the reason it's not working is due to the menu. The menu has a single button and two text elements, which are fine. The code that I'm using on the menu is this:
import flash.events.MouseEvent;
stop();
var format:TextFormat = new TextFormat();
format.size = 26;
format.bold = true;
playGameButton.setStyle("textFormat", format);
stage.addEventListener(MouseEvent.CLICK, playGame);
function playGame(e:MouseEvent) {
if(e.target.name == "playGameButton") {
gotoAndStop(2);
}
}
If I use just gotoAndStop(2); it works fine, but with everything else it just goes to the second frame, and nothing else works after that.
Edit #2: I've narrowed it down even farther to the if statement itself.
if(e.target == playGameButton)
if(e.target.name == "playGameButton")
Both of those don't work. If I just remove the if statement all together it works perfectly fine.
there seems to be aproblem with this lines
if(getChildAt(i) is platform)
leads to error 1067: Implicit coercion of a value of type flash.display:MovieClip to an unrelated type Class
the rest of the code seems to be just fine
Try disabling your buttons mouseChildren.
playGameButton.mouseChildren = false;
Try e.currentTarget instead of e.target. From the documentation:
currentTarget : Object
[read-only] The object that is actively processing the Event object with an event listener.
target : Object
[read-only] The event target.
I'm not quite sure that this is your problem but the target vs currentTarget confusion has gotten me before.

As3 How to flip a movieclip to face movement direction?

Working on a maze game. When the leftkey is pressed the movieclip (char) should turn 90 degrees to the left.
Correct me if i'm wrong but I thought I could use this code;
char.scaleX *= -1;
However, the most important thing is that the character doesnt go through the walls of the maze.
And I think thats my problem for implementing the code above.
Because it doesnt work properly when i put in here;
if(!mazehit) {
char.y += speed;
char.scaleX *= -1;
}
My question to you is, where do I have to put the code to flip the movieclip?
var leftArrow, rightArrow, upArrow, downArrow:Boolean;
var speed:Number = 4;
var charRadius:Number = 10;
stage.addEventListener(KeyboardEvent.KEY_DOWN, keyPressed);
stage.addEventListener(KeyboardEvent.KEY_UP, keyReleased);
stage.addEventListener(Event.ENTER_FRAME, everyFrame);
function keyPressed(event:KeyboardEvent):void {
if (event.keyCode == Keyboard.LEFT) {
leftArrow = true;
}
if (event.keyCode == Keyboard.RIGHT) {
rightArrow = true;
}
if (event.keyCode == Keyboard.UP) {
upArrow = true;
}
if (event.keyCode == Keyboard.DOWN) {
downArrow = true;
}
}
function keyReleased(event:KeyboardEvent):void {
if (event.keyCode == Keyboard.LEFT) {
leftArrow = false;
}
if (event.keyCode == Keyboard.RIGHT) {
rightArrow = false;
}
if (event.keyCode == Keyboard.UP) {
upArrow = false;
}
if (event.keyCode == Keyboard.DOWN) {
downArrow = false;
}
}
function everyFrame(event:Event):void {
var mazehit:Boolean = false;
if (leftArrow) {
for(var i:int = 0; i < speed; i++) {
if(bounds.hitTestPoint(char.x - charRadius - i, char.y, true)) {
mazehit = true;
break;
}
}
if(!mazehit) {
char.x -= speed;
}
} else if (rightArrow) {
for(var j:int = 0; j < speed; j++) {
if(bounds.hitTestPoint(char.x + charRadius + j, char.y, true)) {
mazehit = true;
break;
}
}
if(!mazehit) {
char.x += speed;
}
} else if (upArrow) {
for(var k:int = 0; k < speed; k++) {
if(bounds.hitTestPoint(char.x, char.y - charRadius - k, true)) {
mazehit = true;
break;
}
}
if(!mazehit) {
char.y -= speed;
}
} else if (downArrow) {
for(var m:int = 0; m < speed; m++) {
if(bounds.hitTestPoint(char.x, char.y + charRadius + m, true)) {
mazehit = true;
break;
}
}
if(!mazehit) {
char.y += speed;
}
}
}
thank you for your time
I would update the direction depending on the speed:
char.scaleX = (speed > 0) ? 1 : -1;
Or, by the keys that have been pressed:
if(keyLeft && !keyRight)
{
char.scaleX = -1;
}
else if(keyRight && !keyLeft)
{
char.scaleX = 1;
}
else
{
// keep current direction
}