collision as3 dectect - actionscript-3

hi im trying to make a basic game on adobe flash as3 to help learn collision dection, the aim is to make your way through traffic. the player (box_MC) has to make it to the other side and the other objects are in the way (cycle) which have collision detection. i did the collision detection by going into cycle movieclip and making other smaller cycles which if you hit creates collision.
the collision error lies with if the player moves down onto the cycle it doesnt run the collision
p.s if there is a better way of doing the collision how is it done?

hitTestObject() and hitTestPoint() aren't very good when it comes to collision detection, which is somewhat ironic since, of course, those are the first things most people look at when trying to implement collisions. However, I've found that simple math (like, really simple) combined with an equally simple while() loop is the best way to go about it.
What I do is:
// the stage collision box
var mStageRect:Rectangle = new Rectangle(/*stage collision box properties here*/);
// create a Point object that holds the location of the bottom center of the player
var mPlayerBase:Point = new Point(player.x + (player.width / 2), player.y + player.height);
// call this function every frame through your game loop (onEnterFrame)
private function checkCollision(e:Event):void
{
// while the player's bottom center point is inside of the stage...
while (rectContainsPoint(mStageRect, mPlayerBase))
{
// decrement the player's y
player.y--;
// set gravity to 0
player.gravity = 0;
// set isOnGround to true
player.isOnGround = true;
}
}
// checks if a point is currently positioned within the bounds of a rectangle object using ultra simple math
private function rectContainsPoint(rect:Rectangle, point:Point):Boolean
{
return point.x > rect.x && point.x < rect.x + rect.width && point.y > rect.y && point.y < rect.y + rect.height;
}
This is waaaaaaay more efficient than hitTestObject/Point, imo, and has given me no problems.

Related

As3: Not move through objects? How is the logic behind this?

I have a function where I can control my character.
I also have a movieclip on the stage called assassin_table.
I want to make it so that the character can't move in the table, a.k.a make the table work like a wall.
I have this code:
if(!this.hitTestObject(_root.assassin_table))
{
if(upKeyDown)
{
gotoAndStop(4);
y-=Math.cos(rotation/-180*Math.PI)*(mainSpeed +7);
x-=Math.sin(rotation/-180*Math.PI)*(mainSpeed +7);
}
if(!upKeyDown)
{
gotoAndStop(3);
}
}
However, if I touch the table, then I can't move at all.
I know it's because if(!this.hitTestObject(_root.assassin_table)), but I don't understand the logic behind NOT moving through objects. I'd much rather have a near pixel-perfect collision detection system, but since it's so hard to find any good info online which isn't confusing, I'll stick with hitTestObject for now :)
EDIT: Tried something, didn't really work that well.
if(!_root.assassinDead && !teleporting && this.currentFrame != 5)
{
if(this.hitbox.hitTestObject(_root.assassin_table))
{
_root.assassin_table.gotoAndStop(2);
if(this.x > _root.assassin_table.x)
{
trace("Can't move right");
canMoveRight = false;
}
if(this.x <_root.assassin_table.x)
{
trace("Can't move left");
canMoveLeft = false;
}
if(this.y > _root.assassin_table.y)
{
trace("Can't move up");
canMoveUp = false;
}
if(this.y < _root.assassin_table.y)
{
trace("Can't move down");
canMoveDown = false;
}
}
else
{
canMoveRight = true;
canMoveLeft = true;
canMoveUp = true;
canMoveDown = true;
}
}
This causes me to sometimes be able to walk through the table. I figure it's because my character can move in essentially every possible angle (since he's always facing the mouse and there are no tiles/grids).
How would I make it so that it would work with the advanced movement I have?
Moving up runs this:
y-=Math.cos(rotation/-180*Math.PI)*(mainSpeed +7);
x-=Math.sin(rotation/-180*Math.PI)*(mainSpeed +7);
And the rotation is decided by this:
this.rotation = Math.atan2((stage.mouseY - this.y), (stage.mouseX - this.x)) * 180/ Math.PI + 90;
You should seperate your hittest functions for four different moving directions.
I mean, you shouldn't use this "hitTestObject" stuff, that only returns a boolean value "true" or "false", and that's not going to work for you.
You need a function like "testPoint(player.x, player.y);" and returns the object at the given position, so you can implement it for your game like that
if (upKeyDown && testPoint(player.x, player.y - mainSpeed +7) == null) y-=Math.cos(rotation/-180*Math.PI)*(mainSpeed +7);
player.y - mainSpeed +7 // that checks for plus mainSpeed+7 because of trying to stop your player before it get stack inside object
Basically your logic flow should be like this:
Sample input (key press)
Move character
Check for collisions
If collision then move character to it's "outside" the object that it's touching
In your particular case, if your character is on the left of the table, and you're moving right, then first things first, you move your character. At your new position, check for any collisions. If you have a collection, then because you were moving from the left, we want to be on the left of the object that we colliding with, in this case the table, so we position our character to the left of the table.
The first part of that (checking if the character has hit the table) is called collision detection. Moving the character so that it's outside the bounds of the table is called collision response. Collision detection is a pretty big field and really depends on the type of game you're making; you can do grid-based, hit-test based (if you don't have a ton of objects), physics-based, math-based etc. Collision response can be anything and everything, depending on how you want to react to a collision - you can destroy the object (balloon on a spike), change its speed (character running through mud), bounce off it (ball off wall), or stop any further movement (character against wall).
To make things a bit easier:
Separate your systems - your input shouldn't be dependant on your collision for example. If the up key is down, just register that fact - what you do with it later (make your character move) is up to you
Separate your objects position in memory from its position on screen - this will let you move it around, react to collisions etc, and only when everything is good, update the graphics (stops things like graphics entering a wall only to jump out the next frame)
Solve for one axis at a time - e.g. collide on the x axis first, then the y
Pixel perfect collision is rarely needed :) Non-rotated boxes and circles will work a lot more than you'd think
Somewhat related - the shape of your object doesn't have to be the shape that you're colliding with - e.g. your table collision shape could just be a box; your character collision shape could just be a circle
Update
This causes me to sometimes be able to walk through the table
Assuming that we're going to collide our character and table as boxes, you need to take into account their sizes - i.e. we don't just compare the x values, but the right side of our character box against the left side of the table box etc. Something like:
// assumes objects have their anchor point in the top left - if its
// not the case, adjust as you see fit
if( char.x + char.width > table.x ) // right side of the char is overlapping the left side of the table
canMoveRight = false;
else if( char.x < table.x + table.width ) // left side of char vs right side of table
canMoveLeft = false;
// etc
When working with collisions, it's always nice to see the actual boxes, for debugging. Something like this:
var debug:Shape = new Shape;
debug.addEventListener( Event.ENTER_FRAME, function():void
{
debug.graphics.clear();
debug.graphics.lineStyle( 2.0, 0xff0000 );
// char (again assuming anchor point is top left)
debug.graphics.drawRect( char.x, char.y, char.width, char.height );
// table
debug.graphics.drawRect( table.x, table.y, table.width, table.height );
});
// add our debug. NOTE: make sure it's above everything
stage.addChild( debug );

How do you add gravity with wall collision in actionscript 3?

I created a script that allows your character to move around with wall collision for every direction. How do I add gravity to it on the y-axis and still have it work the same way (like a platform game)?
I tried something like char.y-- when it hits the platform if it were just the floor, but all that does is slowly bring char up no matter where it is in the object, and once it reaches the top, it shakes like crazy.
A preview of the stage: http://puu.sh/63Y1g.png
//WALL COLLISION
if(walls.hitTestPoint(char.x-(char.width/2),char.y,true) && Key.isDown(Key.A)){
char.x+=5
}
if(walls.hitTestPoint(char.x+(char.width/2),char.y,true) && Key.isDown(Key.D)){
char.x-=5
}
if(walls.hitTestPoint(char.x,char.y-(char.height/2),true) && Key.isDown(Key.W)){
char.y+=5
}
if(walls.hitTestPoint(char.x,char.y+(char.height/2),true) && Key.isDown(Key.S)){
char.y-=5
}
//CHARACTER CONTROLS
char.x+=0;
if(Key.isDown(Key.A)){
char.x+=-5;
speed=-5;
}
if(Key.isDown(Key.D)){
char.x+=5;
speed=5;
}
if(Key.isDown(Key.W)){
char.y+=-5;
speed=5;
}
if(Key.isDown(Key.S)){
char.y+=5;
speed=5;
}
To do this really simply, something like this would suffice:
// Check if there is a floor below the char
if (!floor.hitTestPoint(char.x, char.y + (char.height/2) + 2 , true))
{
// If not, apply Gravity
char.y += 5
}
This will only apply gravity if there is no floor 2 pixels directly below the char (this will stop the jittering, feel free to try with different pixel offsets that might work better in your case), I wasn't sure how you were differentiating between the walls and floor, so replace 'floor' with how you are doing it.
===============
If you would like to add realistic accelerating gravity, you will need to add a variable to track the current vertical speed of the char, then add to that each step
eg. Each step do this instead of just adding to y
// Apply gravity
vSpeed += 5
char.y += vSpeed
But if you are going to do that you might as well start getting into vectors and more complex things, there's a lot of materials on the net for this.

AS3 create a trail of movieclips following each other

So, I'm trying to get a few movieclips to follow it's precursor and have the last one follow the mouse. The problem is I'm creating them from code instead of using the interface and, since I'm not an expert, I can't get them to work.
All I have in the library is a MovieClip(linkage:"LETRA") which contains a textField inside(instance name:"myTextField").
Here's what I have:
import flashx.textLayout.operations.MoveChildrenOperation;
import flash.display.MovieClip;
import flash.events.Event;
//this are the letters that will be following the mouse
var phrase:Array = ["H","a","c","e","r"," ","u","n"," ","p","u","e","n","t","e"];
//variable to spread them instead of creating them one of top of each other
var posXLetter:Number = 0;
//looping through my array
for (var i:Number = 0; i < phrase.length; i++)
{
//create an instance of the LETRA movieclip which contains a text field inside
var newLetter:MovieClip = new LETRA();
//assing a letter to that text field matching the position of the phrase array
newLetter.myTextField.text = phrase[i];
//assign X position to the letter I'm going to add
newLetter.x = posXLetter;
//add properties for storing the letter position
var distx:Number = 0;
var disty:Number = 0;
//add the listener and the function which will move each letter
newLetter.addEventListener(Event.ENTER_FRAME, moveLetter);
function moveLetter(e:Event){
distx = newLetter.x - mouseX;
disty = newLetter.y - mouseY;
newLetter.x -= distx / 10;
newLetter.y -= disty / 10;
}
//add each letter to the stage
stage.addChild(newLetter);
//increment the next letter's x position
posXLetter += 9;
}
With that code, only one letter is following the mouse (the "E") and the rest are staying where I added them using addChild and the posXLetter variable.
Also, I'm trying to get it to behave more like a trail, so if I move up, the letters will lag beneath me; if I move to the left, the letters will lag to my right but I think that with my current approach they will either A) move all together to the same spot or B) always hang to the left of the cursor.
Thanks for any possible help.
This is a kind of motion called Inverse Kinematics and it is a quite popular way to make rag dolls in games. It uses a design pattern called the Composite Pattern where one object adds another object as a child of its and then when it's update() function if called, it calls all of its (usually one) child's update() functions. The most common example of this is of a snake. The snake's head follows your mouse, and the rest of the snake's body pieces move with the snake, and it looks immensely realistic. This exact example is explained and build here although it does not include joint restrictions at all.
This example is in the middle of a book, and so may be hard to start reading, but if your somewhat familiar with design patterns and/or have some intermediate experience with programming, then i'm sure you can understand it. I advise that you, after reading and understanding the example, scratch what you have now because it is not very elegant coding. You may feel that this example uses too many classes, but trust me, its worth it as it allows you to very easily edit your code, if you decide to change it in the future, with no drawbacks.
Also, i know that this snake is not what you want, but if you understand the concept then you can apply it to your own specific needs.
I hope this helps.
I think it is a scoping issue. You might need to modify your handler
function moveLetter(e:Event){
trace(e.target); //check if this is the right movie clip
distx = e.target.x - mouseX;
disty = e.target.y - mouseY;
e.target.x -= distx / 10;
e.target.y -= disty / 10;
}

AS3: Sprite following a Path in high speed

First of all sorry for some english mistakes. Portuguese is my first language(I am from Brazil)
Im trying to make a space game from scratch in AS3 and the way to move the ship is like in the game Air Traffic Chief.
I succeed at some point. But when the ship is very fast it start to shake and its not very smooth and clean as I want.
Here is what i have done: http://megaswf.com/s/2437744
As the code is very big so I pasted in pastebin: pastebin.com/1YVZ23WX
I also wrote some english documentation.
This is my first game and my first post here. I really hope you guys can help me.
Thanks in advance.
Edit:
As the code is very big i will try to clarify here.
When the user MouseDown and MouseMove the ship every coordinate is passed to an array.
When the user MouseUP this array is passed to a function that fix the array.
For example: If the distance between two coordinates is greater than 5px, the function creates a coordinate in the middle of the two coordinates.
if I take this function off the problem seen to be solved. But if the user move the mouse very slow it still happens. It also creates a problem that i was trying to solve with that function. as the distance of the two coordinates are very big when the ship arrive in one coordinate most of the line path disappear.
I uploaded a version without the function that fixes the array. http://megaswf.com/s/2437775
I think there is 2 ways for solving this problem
1- Try to fix the noise in the array of coordinates 2- Take off the function that create an coordinate between two points and try to fix the problem of the line path disappear.
Here is the 2 important functions:
this function moves the ship
private function mover():void
{
if (caminhoCoords[0]!=null) // caminhoCoords is the array that contain the path
{
var angulo:Number = Math.atan2(this.y - caminhoCoords[0][1], this.x - caminhoCoords[0][0]);
this.rotation = angulo / (Math.PI / 180);
this.x = this.x - velocidade * (Math.cos(angulo));
this.y = this.y - velocidade * (Math.sin(angulo));
var testex:Number = Math.abs(this.x - caminhoCoords[0][0]); //test to see the distance between the ship and the position in the array
var testey:Number = Math.abs(this.y - caminhoCoords[0][1]);
if (testey<=velocidade+2 && testex<=velocidade+2) // if is velocidade+2 close then go to the next coordnate
{
caminhoCoords.shift();
}
}
}
This function draw the line:
private function desenhaCaminho():void //draw the black Path
{
if(caminhoCoords.length>=1)
{
caminho.graphics.clear();
caminho.graphics.lineStyle(1, 0x000000, 1,true);
caminho.graphics.moveTo(caminhoCoords[0][0],caminhoCoords[0][1]);
for (var i:int = 1; i < caminhoCoords.length; i++)
{
caminho.graphics.lineTo(caminhoCoords[i][0], caminhoCoords[i][1]);
}
}else
{
caminho.graphics.clear();
}
}
Every time the ship arrive in one coordinate is take that coordinate off the array and redraw the array.
Is there a better way of doing that?
I believe if you set your registration point of the plane to the centre and use .snapto(path), it will improve the action.
Judging from just the look of the stuttering, I would guess you need to smooth out the "line" a fair bit. It's probably picking up a lot of noise in the line, which is then translated into the rotation of the plane. Either smooth out the rotation/position of the plane, or the line itself.

AS3 - Ball hitting Y coordinate

I'm making a little app for school where you can controll a ball with the Acceleropmeter (for Smartphones) and I want that, if the ball reaches a certain Y coordinate, you lose and you go to another frame (where it says you have lost the game). 've done the ball and the code so far is this:
var fl_Accelerometer:Accelerometer = new Accelerometer();
fl_Accelerometer.addEventListener(AccelerometerEvent.UPDATE, fl_AccelerometerUpdateHandler);
function fl_AccelerometerUpdateHandler(event:AccelerometerEvent):void
{
cBall.x -= event.accelerationX * 40;
cBall.y += event.accelerationY * 40;
}
cBall.addEventListener(Event.ENTER_FRAME, moveBall);
function moveBall(evt:Event){
// this is to stop the ball when it tries to exit the sreen
if(cBall.x > (480-cBall.width/2)){
cBall.x = 480-cBall.width/2;
}
// except for this, that stops the ball not if it touches the end of the screen, but if it reaches a certain Y coordinate
if(cBall.y > (780-cBall.width/2)){
gotoAndStop(3);
}
if(cBall.x < (0+cBall.width/2)){
cBall.x = 0+cBall.width/2;
}
if(cBall.y < (0+cBall.width/2)){
cBall.y = 0+cBall.width/2;
}
}
Whenever I try the app, it says there is an error in the 32nd line (TypeError: Error #1009: Cannot access a property or method of a null object reference.
at ballApp_Scene1_fla::MainTimeline/moveBall()[ballApp_Scene1_fla.MainTimeline::frame1:32) Why? How can i fix this?
Since cball is the only object used in the moveBall-function, the null pointer exception means cBall was not yet initialized. Since this part is not shown there is no big help possible..
But maybe take a look at collision detection and the
BitmapData Class and its method hittest :
http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/display/BitmapData.html#hitTest%28%29
or DisplayObject Class offers hitTestPoint and hitTestObject
http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/display/DisplayObject.html#hitTestObject%28%29
If you can make different maps and object with image data and transparency it becomes easier to handle than hardcode each x and y coordinate to handle.
another one trying to do similar stuff:
BitmapData Collision