AS3 Collision Detection through hitTestPoint for a map based game - actionscript-3

I am trying to work out the best way to perform a hitTestPoint for a game with a character, enemies and objects that are non-walkable in the map.
I have created a version that works, which can be seen here:
http://www.hosted101.net/hit/mapHitTest.html (arrow keys to move, you're the square).
Using a previously suggested method, I have created a secondary version of all objects on the map, increased by half the size of the player and am running a hitTestPoint from centerX and centerY of the player.
This is great and works fine.
However, I feel it is not optimal and it could be unnessesary to have all these extra "boundry boxes" created, even if the user can't see them.
So, I created a second version. This time without the boundry boxes:
http://www.hosted101.net/hit/mapHitTestNew.html (arrow keys to move).
As this is still running from centerX and centerY of the player, if you approach an object but are below centerX/Y, you will be able to travel through it.
My question is this: to hitTest objects vs players/enemies/anything on a game like this, what is the best method? (with a fixed example for this simple project would be great)
Is it really creating a duplication of the map layer with additional bounding boxes, or can it be done in a more clean way?
My code is below, for mapHitTestNew.
Thanks.
var moveL:Boolean = new Boolean
var moveR:Boolean = new Boolean
var moveU:Boolean = new Boolean
var moveD:Boolean = new Boolean
var moveSpeed:int = 2
stage.addEventListener(KeyboardEvent.KEY_DOWN, updateKeysDown)
stage.addEventListener(KeyboardEvent.KEY_UP, updateKeysUp)
function updateKeysDown(e:KeyboardEvent){
var _keyCode = e.keyCode
switch (_keyCode){
case 37:
moveL = true;
break;
case 38:
moveU = true;
break;
case 39:
moveR = true;
break;
case 40:
moveD = true;
break;
}
collisionCheck()
}
function updateKeysUp(e:KeyboardEvent){
var _keyCode = e.keyCode
switch (_keyCode){
case 37:
moveL = false;
break;
case 38:
moveU = false;
break;
case 39:
moveR = false;
break;
case 40:
moveD = false;
break;
}
}
/**
***
*** Hit Test
***
***
**/
function collisionCheck():void{
var _MC:MovieClip = new MovieClip;
_MC.x = player.x
_MC.y = player.y
_MC.mouseEnabled = false
var centerX:Number = _MC.x + (player.width/2)
var centerY:Number = _MC.y + (player.height/2)
if(moveL){
trace("Stage 1 Move")
centerX -= moveSpeed
if(map.hitTestPoint((centerX-player.width/2), centerY, true)){
trace("Stage 1 HIT TEST!")
moveL = false
}
}
if(moveR){
trace("Stage 2 Move")
centerX += moveSpeed
if(map.hitTestPoint((centerX+player.width/2), centerY, true)){
trace("Stage 2 HIT TEST!")
moveR = false
}
}
if(moveU){
trace("Stage 3 Move")
centerY -= moveSpeed
if(map.hitTestPoint(centerX, (centerY-player.height/2), true)){
trace("Stage 3 HIT TEST!")
moveU = false
}
}
if(moveD){
trace("Stage 4 Move")
centerY += moveSpeed
if(map.hitTestPoint(centerX, (centerY+player.height/2), true)){
trace("Stage 4 HIT TEST!")
moveD = false
}
}
refreshMovement()
}
function refreshMovement():void{
if(moveL){
player.x -= moveSpeed
}
if(moveR){
player.x += moveSpeed
}
if(moveU){
player.y -= moveSpeed
}
if(moveD){
player.y += moveSpeed
}
}

It sounds like you're doing a kind of over-head view (considering you have the box moving in X and Y). I would have an 2D array with 0's and 1's in it (true/falses). When your character moves around, look up your characters hit box for the tiles that it occupies, which will generally be 1 to 4 tiles.
If there is a TRUE in any of thoses spots, he is hitting something. This way you only need hit boxes on objects that are active (they move etc)
I would also check out this article, and implement the solution that seems to work best for you:
http://higherorderfun.com/blog/2012/05/20/the-guide-to-implementing-2d-platformers/

Related

AS3 Character jumping/falling problems

I am having problems with getting the character to jump/fail when the up arrow is pressed. I'm trying to make it so when the up arrow key is pressed once it will jump a certain height then fall.
Here is my movement code:
public var gravity:int = 2;
public function fireboyMovement(e:KeyboardEvent):void
{
if (e.keyCode == 37) //right
{
fireboy1.x = fireboy1.x -5;
checkBorder()
}
else if (e.keyCode == 39) //left
{
fireboy1.x = fireboy1.x +5;
checkBorder()
}
if (e.keyCode == 38) //up
{
fireboy1.y = fireboy1.y -20;
fireboy1.y += gravity;
checkBorder()
}
Your issue is you need to increment the players position over time (and not all at once).
You can either use a tweening engine (like tweenlite), or roll your own timer or enter frame handler.
Here is an example of the latter:
if (e.keyCode == 38) //up
{
if(!isJumping){
isJumping = true;
velocity = 50; //how much to move every increment, reset every jump to default value
direction = -1; //start by going upwards
this.addEventListener(Event.ENTER_FRAME,jumpLoop);
}
}
var isJumping:Boolean = false;
var friction:Number = .85; //how fast to slow down / speed up - the lower the number the quicker (must be less than 1, and more than 0 to work properly)
var velocity:Number;
var direction:int = -1;
function jumpLoop(){ //this is running every frame while jumping
fireboy1.y += velocity * direction; //take the current velocity, and apply it in the current direction
if(direction < 0){
velocity *= friction; //reduce velocity as player ascends
}else{
velocity *= 1 + (1 - friction); //increase velocity now that player is falling
}
if(velocity < 1) direction = 1; //if player is moving less than 1 pixel now, change direction
if(fireboy1.y > stage.stageHeight - fireboy1.height){ //stage.stageheight being wherever your floor is
fireboy1.y = stage.stageHeight - fireboy1.height; //put player on the floor exactly
//jump is over, stop the jumpLoop
this.removeEventListener(Event.ENTER_FRAME,jumpLoop);
isJumping = false;
}
}

Dart key press' to change the direction of a sprite in a 2D game

I have recently been making a game in dart. In the game, the user controls a space ship sprite with the W, A, S and D keys. These will make the sprite move UP. Left, Right and Down respectively. Space will make a square that represents a projectile, missile bullet etc. move at great speed in the direction the ship is facing.
I have a very bad system that works:
(FOR HANDLING KEY PRESS)
bool drawBull = false;
void handleKeyboard(KeyboardEvent event) {
kevent = event.keyCode;
if (kevent == KeyCode.W || kevent == KeyCode.UP){
direction = 'up';
window.console.log('w / up');
}
else if (kevent == KeyCode.A || kevent == KeyCode.LEFT){
direction = 'left';
window.console.log('a / left');
}
else if (kevent == KeyCode.S || kevent == KeyCode.DOWN){
direction = 'down';
window.console.log('s / down');
}
else if (kevent == KeyCode.D || kevent == KeyCode.RIGHT){
direction = 'right';
window.console.log('d / right');
}
else if (kevent == KeyCode.SPACE) {
shotX = lastX; shotY = lastY;
if (direction == 'right') { shotX = shotX + 400; }
if (direction == 'down') { shotY = shotY + 400; }
drawBull = true;
window.console.log('space');
} else {
return null;
}
}
And the draw function itself:
void draw() {
canvas.width = canvas.width;
switch (direction) {
case 'up':
lastY = lastY - 3;
context.drawImage(shipU, lastX, lastY);
if (drawBull) { shotY = shotY - 30; context.fillRect(lastX + 240, shotY, 20, 20); }
break;
case 'left':
lastX = lastX - 3;
context.drawImage(shipL, lastX, lastY);
if (drawBull) { shotX = shotX - 30; context.fillRect(shotX, lastY + 240, 20, 20); }
break;
case 'down':
lastY = lastY + 3;
context.drawImage(shipD, lastX, lastY);
if (drawBull) { shotY = shotY + 30; context.fillRect(lastX + 240, shotY, 20, 20); }
break;
case 'right':
lastX = lastX + 3;
context.drawImage(shipR, lastX, lastY);
if (drawBull) { shotX = shotX + 30; context.fillRect(shotX, lastY + 240, 20, 20); }
break;
default:
return null;
}
}
As you can see, this is a long untidy and tedious method. However, despite all my brain racking I can't think of a system that avoids these many if/switch statements and the idea of writing out the draw image and shooting code for each one.
My actual game will be heavily object orientated of course, so perhaps an object-orientated solution would be helpful.
The code answer given to this question was quite nice, although doesn't fit my needs exactly. So perhaps an adoption of a class like that would work well How to listen to key press repetitively in Dart for games?
Thank you very much for your help!
-Tom W.
Instead of storing directions as strings, you could store the Velocity and/or Rotation of items, and use that for rendering.
You could then store a map of the key vs the velocity change:
var keyHandlers = {
KeyCode.W: new Point(0, 1),
KeyCode.S: new Point(0, -1),
KeyCode.A: new Point(-1, 0),
KeyCode.D: new Point(1, 0),
}
var spritePosition = new Point(0, 0);
void handleKeyboard(KeyboardEvent event) {
if (keyHandlers[event.keyCode])
spritePosition += keyHandlers[event.keyCode];
}
Ultimately, you probably want to actually store a Velocity for the sprite, and use input to increase the velocity; and then "decay" that velocity each frame (to represent gravity/friction, etc.).
If your sprite needs to be rendered at a particular direction, you should store a rotation as well as position and velocity. There's a simple set of slides here that could be useful; and there are also lots of good XNA tutorials out there that will cover building a "GameObject" class to wrap up this state (although XNA is dead, the tutorials are great, and the C# is not a million miles from Dart).
When your ship shoots, you can copy the position and rotation from the ship to the bullet and calculate it's velocity by applying the ships rotation to the starting velocity of your bullet.
There's also a great website by Bob Nystrom at gameprogrammingpatterns.com that I'd recommend reading as you get more into it.

How to call AS3 Switch

I am struggling a bit with my switch statement (I've never used switch before). I have a hit test for when my object reaches the top or bottom of the stage. When this happens, I want to switch states (the game in question is a simple platformer that allows the player to switch the gravity when they hit a new surface. Below is my current code:
{
...
if(player.hitTestObject(bottom)) {
//Switch state to normal
}
if(player.hitTestObject(top)) {
//Switch state to inverted
}
}
switch (myGrav){
case "NORMAL":
trace("Normal")
player.gotoAndPlay(1);
oktoJump = false;
player.y = 376.5;
case "INVERTED":
trace("Inverted")
player.gotoAndPlay(8);
oktoJump = false;
player.y = 12;
}
Thanks!
Cases within your switch statement are missing a break; therefore, code will continue to execute through the switch statement.
This should be:
var myGrav:String = "NORMAL";
if (player.hitTestObject(bottom))
myGrav = "NORMAL";
if (player.hitTestObject(top))
myGrav = "INVERTED";
switch (myGrav)
{
case "NORMAL":
trace("Normal")
player.gotoAndPlay(1);
oktoJump = false;
player.y = 376.5;
break;
case "INVERTED":
trace("Inverted")
player.gotoAndPlay(8);
oktoJump = false;
player.y = 12;
break;
}
I prefer less variables when I can get away with it.
switch (true){
case (player.hitTestObject(bottom)):
trace("Normal")
player.gotoAndPlay(1);
oktoJump = false;
player.y = 376.5;
break;
case (player.hitTestObject(top)):
trace("Inverted")
player.gotoAndPlay(8);
oktoJump = false;
player.y = 12;
break;
}

Camera following object

I am fairly new to coding. I am was wondering if there was a way so when I move my object with keys I can get the camera to keep on my object so I can move around a larger world than just my viewport.
I have tried to move the world around instead of my object but for what I am doing it makes my coding a lot more difficult
Here is the code I have.
stage.addEventListener(KeyboardEvent.KEY_DOWN, keydown );
function keydown (event:KeyboardEvent):void{
switch (event.keyCode){
case Keyboard.LEFT :
ball.x -= 10;
break ;
case Keyboard.RIGHT :
ball.x += 10;
break;
case Keyboard.UP :
ball.y -= 10;
break;
case Keyboard.DOWN :
ball.y += 10;
break;
default :
break;
}
}
you could have the world and the character in a holding sprite/movieclip
then as you move the character, you can set the position of the holder in the opposite direction.
you can use global to local to get the position of the ball, and then can even apply some movement smoothing
here's some code that should work easy enough
you need a movieclip called holder inside that is ball , the holder would also have your world and world assets. And as long as there's no scaling you don't need to use globalToLocal
var middlePt:Point = new Point(stage.stageWidth/2, stage.stageHeight/2);
var pt:Point = new Point(holder.ball.x, holder.ball.y);
var destPoint:Point = new Point(-pt.x + middlePt.x, -pt.y + middlePt.y);
addEventListener(Event.ENTER_FRAME,enterFrame);
function enterFrame(e:Event):void{
holder.x = holder.x*0.5 + destPoint.x*0.5;
holder.y = holder.y*0.5 + destPoint.y*0.5;
}
stage.addEventListener(KeyboardEvent.KEY_DOWN, keydown );
function keydown (event:KeyboardEvent):void{
switch (event.keyCode){
case Keyboard.LEFT :
holder.ball.x -= 10;
break ;
case Keyboard.RIGHT :
holder.ball.x += 10;
break;
case Keyboard.UP :
holder.ball.y -= 10;
break;
case Keyboard.DOWN :
holder.ball.y += 10;
break;
default :
break;
}
middlePt = new Point(stage.stageWidth/2, stage.stageHeight/2);
pt = new Point(holder.ball.x, holder.ball.y);
destPoint = new Point(-pt.x + middlePt.x, -pt.y + middlePt.y);
}

ActionScript 3 - Walls don't collide properly

For several weeks I'm been trying to make my topdown game. It went well for some time, but then at some point I wanted to create a scrolling map with walls everywhere. Now, to make it easy to create the map (and add more later) I made a class called "Wall" which I will hit test. This works, when it hits, the map must stop scrolling. It does, so good so far.
Now, when the player moves away from the object, I want the map to be able to scroll again, this works too, but now the player can't move to the side the player came from. I know this is because I need to define the sides, where the player enters, in order tell the game which movement must be set to zero at that point.
You can see the code here:
public function AddWalls(player:MovieClip)
{
WallObjects = new Array();
for (var i:int = 0; i < this.numChildren; i++)
{
var mc = this.getChildAt(i);
if (mc is Wall)
{
var wallobj:Object = new Object();
wallobj.mc = mc;
wallobj.leftside = mc.x;
wallobj.rightside = mc.x + mc.width;
wallobj.topside = mc.y;
wallobj.bottomside = mc.y + mc.height;
wallobj.width = mc.width;
wallobj.height = mc.height;
WallObjects.push(wallobj);
}
}
}
public function EnableCollisionWithWalls():void
{
for (var k:int = 0; k < WallObjects.length; k++)
{
//if (player.y > WallObjects[k].topside && player.y < WallObjects[k].bottomside && player.x > WallObjects[k].leftside && player.x < WallObjects[k].rightside)
if (player.hitTestObject(WallObjects[k].mc))
{
if (player.x > WallObjects[k].leftside && player.x < WallObjects[k].leftside+15)
{
Lefthit = true;
trace(DebugVar);
DebugVar++;
player.x = WallObjects[k].leftside;
Scroll_x = 0;
}
else
if ( player.x < WallObjects[k].leftside -1 || (player.y > WallObjects[k].leftside ))
{
Lefthit = false;
}
if (player.hitTestObject(derp))
{
Lefthit = false;
}
}
}
}
public function EnableMovement():void
{
map.x += Scroll_x;
map.y += Scroll_y;
for (var i:int = 0; i < this.numChildren; i++)
{
var mc = this.getChildAt(i);
if (mc is Wall)
{
mc.x += Scroll_x;
mc.y += Scroll_y;
}
}
}
public function MovementKeysDown(move:KeyboardEvent):void
{
var Speed:int = -5;
switch (move.keyCode)
{
case 37: // venstre knap
Scroll_x = -Speed;
break;
case 38: // op
Scroll_y = -Speed;
break;
case 39: // højre knap
Scroll_x = Speed;
if (Lefthit)
{
Scroll_x = 0;
}
break;
case 40: // ned
Scroll_y = Speed;
break;
default:
}
}
public function MovementKeysUp(move:KeyboardEvent):void
{
switch (move.keyCode)
{
case 37:
Scroll_x = 0;
break;
case 38:
Scroll_y = 0;
break;
case 39:
Scroll_x = 0;
break;
case 40:
Scroll_y = 0;
break;
default:
}
}
Might be some syntax errors (since I removed some code in this editor).
You can see the current version here.
In this version the scroll keeps on going. I did come up with a "fix" for it, by check if the player was 1 pixel away from the movieclip, inside the hit test (which for some reason works, which I guess it shouldn't since it doesn't hit anymore) and then setting the Lefthit to false. However this is not a good solution and if you continue up or down away from the movieclip, you are still not able to go right anymore...
I've been baffled by this for a long time, so I thought it was about time I asked for help. I couldn't find anything on how to control movement in a top-down game, with a scrolling map + wall :/
The simplest (but not most resource friendly) solution (if you anyway have a single storage for walls) is iterating through the walls and instead of using the Flash default hitTest (I don't like the way it works since ActionScript 2) - just check the coordinates and if you see that there's going to be a collision on the next simulation step - handle it according to the game logic.
The most useful optimization for this algorithm is creating a filter/data structure for getting only walls that are near to the player and so can be affected to the test for collisions.