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 :
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.