Actionscript3 Simple platform collision confusion - actionscript-3

I'm making a 2D platformer game and i'm trying to add collisions to the platforms so that when the character hits it it cannot pass through. I'm struggling to find the syntax to use to create this collision. So far this is what I have.
Also i would still like to be able to use hitTestObject within the if statement.
thanks
public function platform1Collision():void
{
if (fireboy1.hitTestObject(Platform1))
{
//fireboy1 cannot pass through
}
}

You'll probably want to prevent fireboy1's y property from extending past Platform1's y property:
function platform1Collision():void
{
if(fireboy1.hitTestObject(Platform1))
{
if(fireboy1.y > Platform1.y)
{
fireboy1.y = Platform1.y + Platform1.height;
}
else
{
fireboy1.y = Platform1.y - fireboy1.height;
}
}
}
NOTE: The above code sample assumes top-left orientation for both fireboy1 and Platform1.
EDITED: The above edited code will allow fireboy1 to walk beneath Platform1, but not pass through it.
This is a very rudimentary example to give you an idea of the type of logic you can use. If you want to allow fireboy1 to pass through Platform1 from below, you'll have to update the logic to allow for that. For example, if you take out the if/else and just automatically place fireboy1 above Platform1 every time they collide, it will appear as if player1 is jumping onto Platform1 when it is approached from below.

Related

Check the existence of an object instance

I'm surprised I don't know how to do this, but as it turns out I really don't; simply put, I'm trying to make a side-scrolling shooter game, a basic one and in it, I have 50 stars spawned on-screen through a "for" loop upon the game starting. There is a function which does this and a listener is at the beginning. Problem is, when you lose the game and go back to main menu, 50 more stars would be spawned, which isn't what I want. So, I'm trying to make an "if" statement check at the beginning, so that the game checks whether there is an instance/movie clip of the star object/symbol before determining whether the function that spawns stars should be called out with a listener. So, how do I do this? I looked through some other checks and they didn't help as the codes presented were vastly different there and so I'm just getting errors.
Let me know if a better explanation is needed or if you would like to see some of the code. Note that the game overall already has a lot of code, so just giving all of it would probably not be helpful.
I suggest you rethink your approach. You're focusing on whether stars have been instantiated. That's ok but not the most basic way to think about it.
I would do this instead
private function setup():void{
loadLevel(1);
addListeners();
loadMusic();
// etc...
// call all functions that are needed to just get the app up and running
}
private function loadLevel(lev:int):void{
addStars();
// call all functions that are needed each time a new level is loaded
}
private function restartLevel():void{
// logic for restarting level,
// but this *won't* include adding star
// because they are already added
}
There are other ways to do this but this makes more sense to me than your approach. I always break my game functions into smaller bits of logic so they can be reused more easily. Your main workhorse functions should (IMHO) primarily (if not exclusively) just call other functions. Then those functions do the work. By doing it this way, you can make a function like resetLevel by assembling all the smaller functions that apply, while excluding the part about adding stars.
Here's what I did to solve my problem... Here's what I had before:
function startGame():void
{
starsSpawn();
//other code here
}
This is what I changed it to:
starsSpawn();
function startGame():void
{
//other code here
}
when you said existance, so there is a container, i named this container, (which contain stars , and stars was added to it) as starsRoot, which absolutely is a DisplayObject (right?)
now, to checking whole childrens of a DisplayObject, we have to do this :
for (var i:int=0; i<starsRoot.numChildren; i++) {
var child = starsRoot.getChildAt[i];
}
then, how to check if that child is really star!?
as you said
whether there is an instance/movie clip of the star
so your stars's type is MovieClip, and they don't have any identifier (name), so how to find them and make them clear from other existing movieclips. my suggestion :
define a Linkage name for stars from library, thats a Class name and should be started with a capital letter, for example Stars
now, back to the code, this time we can check if child is an instance of Stars
for (var i:int=0; i<starsRoot.numChildren; i++) {
var child = starsRoot.getChildAt[i];
if (child is Stars) {
// test passed, star exist
break;
}
}

How can i get a function to use any movie clip?

I'm a little lost in understanding this kind of function, i get the feeling this has been asked a thousand times but cannot find an explanation of what the code is doing.
Basically i just want a movie clip with instance name box to do something, then reuse the function for other movie clips afterwards
a little like this, but working.
Many Thanks
//my function to be used on "instance name" box
myfunc (box);
function myfunc ();
{
while (this is happening);
{
//in this case box.x = goes where ever i put it
.x = goes here
.y = goes here
}
}
Sorry it's not quite English, my communication skills are terrible
Sure you can do that. You give the function a parameter, then refer to a parameter to change its properties. With such a simple movement function it could accept a DisplayObject - a distant superclass of a MovieClip and thus a superclass to many other possible classes of those objects that can be displayed by Flash.
function myfunc(param:DisplayObject):void {
// no semicolon after declaring the function!
while (somethingIsHappening(param)) {
// why not call a query on that object?
param.x+=1; // move right by 1 pixel
}
}
You might want to look at this manual on ActionScript 3 syntax, and the following pages on variables, functions and classes, to learn more.

How to drag a symbol only horizontally?

I'm currently trying to make a pretty simple drag and drop Flash program.
I made a program in which you can drag a square with your mouse.
However I would like the square only to move horizontally. I've been trying to find something on the internet pretty long now, without a finding a solution. So I thought maybe you guys could help me...
Here's what I've done:
I first made a square and made a symbol of it named: "blok"
Then I wrote the following code within the same scene:
var myblock:Sprite = blok;
this.addChild(myblock);
myblock.addEventListener(MouseEvent.MOUSE_DOWN, startMove);
function startMove(evt:MouseEvent):void
{
myblock.startDrag();
}
myblock.addEventListener(MouseEvent.MOUSE_UP, stopMove);
function stopMove(e:MouseEvent):void
{
myblock.stopDrag();
}
startDrag takes a bounding box parameter. Try this:
function startMove(evt:MouseEvent):void
{
myblock.startDrag(false, new Rectangle(0, myblock.y, 1000, myblock.y));
}
The 0 and 1000 are min and max x values, substitute whatever you need to use in your application.
Adobe documentation for Sprite class

flash error 1010 when trying to snap a puzzle piece

i am trying to create a puzzle game and so far had no problems with moving the pieces and all but when i tried to check piece position after stopDrag i got an error message:Error #1010: A term is undefined and has no properties.
this is the relevant code:
full1 is a movieclip that contains a picture of the puzzle with a low alpha and the puzzle pieces,each with it's own instance name.
in this example tr is an instance name of one of the pieces.
public function Move(even:MouseEvent)
{
even.target.startDrag();
}
public function stopMove(even:MouseEvent)
{
this.stopDrag();
checkPos(even.target.name);
}
public function checkPos(nameStr:String)
{
if(nameStr=="tr1")
{
if(this.full1.tr1.x>=460&&this.full1.tr1.x<=465.5&&this.full1.tr.y>=99&&this.full1.tr.y<=103)
{
this.full1.tr.x=460.2;
this.full1.tr.y=101.95;
}
}
}
if anyone sees any problem with what i wrote or has a better idea of how to approach this i would appreciate your help.
thanks.
Looks like it should be even.target.stopDrag() instead of this.stopDrag() (since you started the drag on even.target). Unless the error is occurring after stopDrag(), in which case it doesn't look like enough info to answer.
Side note, it would be better to do the name checking outside of the checkPos() function. e.g.:
this.stopDrag();
if(even.target.name == "tr1")
{
checkPos();
}
And remove the name checking from checkPos().
On one occasion, you use "even.target.startDrag();" to start dragging.
But in the other function, you use "this.stopDrag();" to stop dragging.
You should either always use "this" or always use "even.target". This could be the cause of your error.
It would also be good to know in which line exactly the crash happens.

Game logic and game loops in ActionScript 3

I am making a Shooting game in flash actionscript 3 and have some questions about the flow of logic and how to smartly use the OOPs concepts.
There are mainly 3 classes:
Main Class: Initializes the objects on the screen.
Enemy Class: For moving the enemies around on the screen.
Bullet Class: For shooting.
What I want to do is find out if the Enemy has been hit by a bullet and do things which must be done as a result ...
What I am doing right now is that I have a ENTER_FRAME event in which i check collision detection of each enemy unit (saved in an array) with the bullet instance created, and if it collides then perform all the necessary actions in the Main class .. clogging the Main class in the process ..
Is this the right technique ? or are there better solutions possible ?
Try to think more OOP, what is every object responsible for?
We have the enemies wich we can hit:
class Enemy : extends NPC implements IHittable {
. . .
function update(delta) {
// move, shoot, etc.
}
function handleHit(bullet) {
// die
}
}
A hittable object:
interface IHittable {
function handleHit(bullet);
}
The bullet is suppose to move and hit things:
class Bullet : {
function update(delta) {
// update position
}
function checkHits(world:World) {
for each(var hittable:IHittable in world.objects) { // might want to cluster objects by location if you're handling lots of objects / bullets)
if (isColidingWith(hittable))
o.handleHit(bullet);
}
}
}
And then we have the world with everything inside:
class World {
var npcs: Array ...
var bullets: Array ...
var hittables: Array ...
function update(delta) {
foreach(var c:NPC in npcs)
c.update(delta);
foreach(var b:Bullet in bullets) {
b.update(delta);
b.checkCollisions(world);
}
}
}
And your main loop is just simple as that:
var lastTime:int;
function onEnterFrame(...) {
var now:int = getTimer(); // FlashPlayer utility function to get the time since start (in ms)
world.update(now - lastTime);
lastTime = now;
}
A few other notes:
try to do all the computation based on a delta of time, otherwise the game's speed will vary with the framefrate.
what happens when a character dies? bullet disappear? Well, you could do it several ways:
fire an event, like EnemyDied and remove it from the world
implement an interface CanDie that has a (get dead():Boolean property) and use that to cleanup the world at every update.
but don't write the code to remove the enemy in the Enemy class, because then you will be polluting the class with code that should be handled by the World, and that will be hard to maintain later.
Sorry for the long answer, but I couldn't help myself :)
Was clogging the Main class the problem, or finding out what bullet hit what enemy the problem? If it was the bullet, you need to describe the bullet behavior - can it hit multiple enemies, how fast does it move (is it possible that when testing using "enterFrame" the bullet will first appear in front of the enemy, and, on the second frame, it will appear behind the enemy?). May enemy be simplified to some basic geometrical shape like circle or rectangle, or do you need pixel-perfect precision? Finally, how many bullets and how many enemies are you planning to have at any one time? It could be too expensive to have a display object per bullet, if you are going to have hundreds of them, and then it could make more sense to draw them into single shape / bitmapdata.
If the problem is that the Main class is too long, there are several possibilities here.
A nobrainer answer to this problem - use inheritance to simply put parts of the code in separate files. Not the best way, but a lot of people do it.
If you did the first, then you'd realize that there are certain groups of functions you put into superclass and subclasses - this will help you split the "clogged" class into several smaller independent pieces that have more particular specialization.
After you did the second, you may find out that there is certain dependency between how you split the big class into smaller classes, so you can try generating those smaller classes by a certain pattern.
And then you write the clogged code that generalizes those parts you just managed to split.
Above is basically the cycle from more concrete to more generic code. In the process of perfecting the last step, you'll write some concrete code again. And that will move you to the step 1. Lather, rinse, repeat :) In fact, you don't want to write OO code, or procedure code or anything that fashion of the day tells you to do. You want to write good code :) And you do it by moving from more generic to more specific and back to more generic, until it's perfect :P
Probably not the best answer, but you must admit, you didn't give much info to give you more precise answer.