Unity JavaScript OnCollisionEnter with 2D gameObject - function

Im trying to destroy a gameObject (in my case a 2d ball) when my player comes into contact with it with the built-in OnCollisionEnter function. My script is only attached to the player. Both the player, and the ball(battery) have 2d box colliders, and rigidbodies. Perhaps the fact that they are 2d colliders instead of regular has something to do with the problem? Ah! yes I almost forgot to mention the problem; it's not working. Its niether destroying, or printing "hit".... and oh yes, i DID name the ball "battery". thAnks so much I would very much appreciate some help!
UnityScript Code:
function OnCollisionEnter(batt : Collision)
{
if(batt.collider.name == "battery")
{
Destroy(batt.gameObject);
Debug.Log("Hit");
}
}

if you are using unity's 2d toolset, instead of OnCollisionEnter you use OnCollisionEnter2D, and inside the variables, instead of batt: Collision, you need to change it to batt: Collision2D, hope this helps :), also, you said your both objects have 2d box colliders and rigidbodies, make sure it's a 2d rigidbody and not a 3d rigidbody (default)

Well, its hard to debug collisions in Unity, and even harder without knowing your whole project. But a few things:
1) Make sure you have rigidbodies attached to your gameObjects that you want to receive events
2) For your code I'm not too sure ( since I mostly do C# ) but basically:
OnCollisionEnter( Collision batt ){
if ( batt.gameObject.name == "battery" ){
//Do what you want it to do
}
}
I think essentially you might not be pulling in the right name. If that doesn't work, try to place a debugger breakpoint on the OnCollisionEnter to see if it is being called.

Related

Errors when switching scenes in flash AS3

In my little Flash project, I use the Enter Frame Gameloop commands, and I use hittestobject and such then put that function in to the game loop. However, When switching scenes I am bombarded with errors because the objects included in the functions are not on screen anymore. My question is how can I either take those functions out of the game loop when changing from that specific scene, or write the code so it only includes that one specific scene. Like: if current frame = 2, or something in real code form. Thankyou so much I am very appreciative for any replies.
function gameLoop(evnt:Event){
try{
//Write your all codes
}catch(err:Error){
}
}
Use try/ catch.
I don't know the way you change scenes.
Based on your description,I guess the way you change scenes is to go to different frames.Am I right?
If I am right,I think you can declare a variable to mark if you need to do the hittestobject function or other operations.
such as:
gameloop(){
if(!changing)
a.hitTestObject(b)
}

Need a hitTestPoint solution to replace hitTestObject

I need an as3 solution to this collision problem:
I have this code:
else if (objectArray[i].toString().indexOf("meandude") != -1) {
//if the object is a meandude and hits it, game over
if (projectileMC.hitTestObject(objectArray[i])) {
removeEventListener(Event.ENTER_FRAME,mainEnterFrame);loseGame();
which is using the bounding boxes of the projectileMC and meandude (hitTestObject). I'd like it so the center points of the projectileMC and meandude crossing registers the action instead (hitTestPoint). I tried to switch it myself, but I'm not getting it to work.
Thanks
Not clear what your precise problem is without seeing more of your code. But as a first guess I would think you want to solve the following problem:
Your hittest is not being triggered when your projectile hits the "meandude" when you use the hitTestObject.
And
You try to solve the problem by using the hitTestPoint instead?
The test might not trigger simple because your projectile is moving too fast. If the distance between XY_ThisFram before colisison and then XY_NextFrame is bigger than the size of of your "meandude" it won't ever collide. I suggest you don't use hitTestObject to do any collision in your game as it is not reliable, especially for fast moving display objects.
Flash doesn't have a good object-to-object hit test for the general case. If both projectileMC and meandude are bitmaps, you can try BitmapData.hitTest.

Animating from within classes in Actionscript 3 (Not on the timeline), what's the best way?

I've found some stuff online about how to animate in actionscript 3 from within a class, but haven't been able to find a really good tutorial. I want to control the animations from a class because at some point I intend to move from the flash IDE to using flash develop, where I won't have access to the Flash IDE's timeline.
I have to be able to control an initial animation (opening a bag) which joins onto an animation loop (searching through a bag).
The only way I have been able to do this so far is to add an event listener to listen for the initial animation's final frame. Then when initialAnimation.currentFrameLabel = "Last" then I gotoAndStop("animationLoop").
This has been working fine, if a bit time-consuming. I'm just wondering if there's a better, easier way to do it? Can anyone tell me or point me towards a tutorial that does it better? Thanks very much!
Romano
I recommend instead of using an event listener, you use the method addFrameScript. Essentially you can fire a method when a specific frame number is reached.
Read the following question for more information.
actionscript3 whats the point of addFrameScript
It depends on what it is you want to do:
Usually if you are working together with an artist or want to do animations that are non-code driven, the "best way" is usually to listen for something to happen, and then start animations and on last frame of animation (or when you want to return control to code) you create an event, or use a callback or something else to let code notify that animation is complete or reached a certain point.
If you want to do something from code, the easiest way is to use an external animation library.
Tweener (https://code.google.com/p/tweener/)
TweenLite (http://www.greensock.com/tweenlite/)
Using those libraries, you would write something similar to:
function fadeOut():void {
mc.alpha = 1;
Tweener.addTween(mc, {alpha:0, time:0.275, delay:1, onComplete:onDone});
}
function onDone():void {
trace("Animation finished");
}

hitTestPoint with 'shapeFlag=true' doesn't work in AS3

I simply added a sprite in AS3:
Sprite myspr = new Sprite();
myspr.addChild(mybitmap);
addChild(myspr);
Then I added an event. I did hitTestPoint for checking mouse is over my sprite or not.
stage.addEventListener(MouseEvent.MOUSE_MOVE, mouseCheck);
private function mouseCheck(evt:MouseEvent):void {
var xx:int = stage.mouseX;
var yy:int = stage.mouseY;
if(myspr.hitTestPoint(xx, yy, true)) {
...
// I'm checking mouse over here.
}
evt.updateAfterEvent();
}
Problem is: hitTestPoint gives true when mouse comes to full boundary box. But it should give true only if mouse comes on transparent isometric sprite.
Is there a solution for this, thanks in advance.
this should help. You need pixel perfect detection.
Actionscript 3 pixel perfect collision. How to? (learning purposes)
http://www.freeactionscript.com/2011/08/as3-pixel-perfect-collision-detection/
http://www.anotherearlymorning.com/2009/07/pixel-perfect-collision-detection-in-actionscript-3/
http://old.troygilbert.com/2009/08/pixel-perfect-collision-detection-revisited/
There's a few ways I usually do hit testing.
1) The easiest way is to use a an already made class that you can find online. Some people much smarter than me have created complex classes that allow for much better pixel to pixel interaction. The ones listed by Paras are all good. The problem with these is, for newer users, it can be hard to understand all the code and how to implement them. Usually it is simple once you understand what is going on though. You just replace your hit test with the class file and then enter in the correct arguments.
2) Another method is to actually go into the symbol, create a new layer, and then draw a rectangle(just turn the alpha down to 0%) where you want the hit test to work. This may seem like a stupid method, after all we are just confined to a square once again. BUT, it will actually work MUCH better than you'd expect. Just draw the square maybe slightly smaller than the height and width of your character you're detecting the hit test on, and you should be good to go. Give it an instance name (the hit square that is) and then just perform the hitTest with that square instead of the actual sprite. It works wonderfully and is a very simple solution. For what you're explaining though, this sounds like it might not work. This method is more from a gamer standpoint. It looks good when attacking and getting hit by enemies, but isn't necessarily exact. Also, if you want to do this with two characters (maybe a large attack hitting an enemy) simply draw a hit box for both sprites. This is probably a little more basic than using a pre-made pixel perfect hit detection test, but it works extremely well and takes only a few minutes.

leaving and revisting a scene keeping any user input changes the same. Can it be done?

Hi Im relatively new to flash developing and i have a quick question about saving user input. I have a maze scene whereby the user navagates a character around until confronted with another object, when the character hits the object a new scene is opened promting the user to pick a solution to a problem. Once the user clicks the correct answer a box appears saying return to the maze, however when clicked and returned to the maze the character starts back in its original postion, where as I would like the scene to resume where it left off, ie the character is at the point where it collided with the object, the object has dissappeared and the character can resume on the same course.
Thanks for giving this a read I hope it makes sense and some one has a solution for me.
I did have some nice images to explain it better but apprently i need 10 reputation points to upload those.
EDIT: First Id like to say thanks for the rep points you bunch of stars and secondly I know using scenes in flash is seriously cr*p practice and outdated but its the way I learnt all those years ago and seen as Flash itself will be outdated soon Im not really looking to learn another approach using sprites or frames, I just kind of want a fix for this way if poss thank you for answering!
EDIT: Wanting the red rectangle to be removed from the scene once the black square collides with it. It also takes you to the next frame upon doing so. here is my code.
addEventListener(Event.ENTER_FRAME, fl_EnterFrameHandler);
function fl_EnterFrameHandler (event:Event):void
{
if (player.hitTestObject(Risk))
{
removeEventListener(Event.ENTER_FRAME, fl_EnterFrameHandler);
removeChild(Risk);
nextFrame();
}
}
I'd suggest you forget about Scenes! They are old, buggy, bring loads of issues with code and are generally a Bad Pratice!! So if you are just learning AS3, dont learn with Scenes!!
Use MovieClips or Sprites instead. And just add and remove them as you need!
EDIT:
To ur edit ;)
and seen as Flash itself will be outdated soon
thats just plain false and a widespread misinformation. It just has a new purpose like MultiPlattform Game Development. But thats a whole different discussion.
You could solve this by saving the x,y coordinates and then restoring them. But i promise you, you will run in to alot more problems/bugs as you go allong!
Like saved Points and Time. Will you triger the Questionscene again when u place the player on the object(last Position). Save the answers, and so on ...
Changing to DisplayObjects will save you time in the end. Just saying ;)
EDIT2:
your code in the comment should look like this:
function fl_EnterFrameHandler (event:Event):void
{
if (player.hitTestObject(Risk))
{
removeEventListener(Event.ENTER_FRAME, fl_EnterFrameHandler);//remove to prevent errors if it fires again and there is no Object to hitTest
removeChild(Risk);// do what needs to be done on this frame
nextFrame();// and then move to the next
}
}
And following correct convetions and make everybody's life easier reading this, it would look like this!
function fl_EnterFrameHandler (event:Event):void
{
if (player.hitTestObject(risk))
{
removeEventListener(Event.ENTER_FRAME, fl_EnterFrameHandler);//remove to prevent errors if it fires again and there is no Onject to hitTest
removeChild (risk);
nextFrame ();
}
}
i'm probaly confusing u now, just use the top one ;)
EDIT3:
Ok, i just had a butchers at it. It's all on a single Frame now. I would have prefered Classes but that'lljust confuse you.
To add new qestions you just have to dublicate the Question MovieClip in the Library and change texts, leave instance names the same tho, then the code will work as is!
DOWLOAD
It is certainly possible. You would store the characters attributes (e.g. current position) within a variable. Then on returning to your game you would use this variable to set the starting position of your character.
I agree that scenes are not the ideal route you should be taking. Possibly reading a good AS3 book would save you hours/days/weeks in the long run.