Making an object or layer transparent when another object passes over it. (Flash Actionscript 3.0) - actionscript-3

I'm very new to coding and am having trouble finishing the last little bit of a mini game type project for school.
So this is a draft of what the program looks like so far: http://aaronmillard.com/dir/wp-content/uploads/2013/08/Google-Doodle_Roomba.swf
Now what I want the program to do is "vacuum" up the google when the roomba drives over it. The easiest way to achieve this (I think) is to have an exact replica of the carpet layer without the google logo beneath the carpet layer with the google logo. So I would need to code something like "when the object(roomba) passes over object(carpetwithgooglelogo) make object(carpetwithgooglelogo) have 0 opacity." I just can't figure out how to say that in code.
The code as of right now look like this:
// Assign 4 booleans for the 4 arrow keys
var keyUp = false;
var keyDown = false;
var keyLeft = false;
var keyRight = false;
// Add the keyboard event (KEY_DOWN) on the stage
stage.addEventListener(KeyboardEvent.KEY_DOWN, pressKey);
function pressKey(pEvent)
{
// If an arrow key is down, switch the value to true to the assigned variable
if (pEvent.keyCode == 38)
{
keyUp = true;
}
else if (pEvent.keyCode == 40)
{
keyDown = true;
}
else if (pEvent.keyCode == 37)
{
keyLeft = true;
}
else if (pEvent.keyCode == 39)
{
keyRight = true;
}
}
// Add the keyboard event (KEY_UP) on the stage
stage.addEventListener(KeyboardEvent.KEY_UP, releaseKey);
function releaseKey(pEvent)
{
// If the arrow key is up, switch the value to false to the assigned variable
if (pEvent.keyCode == 38)
{
keyUp = false;
}
else if (pEvent.keyCode == 40)
{
keyDown = false;
}
else if (pEvent.keyCode == 37)
{
keyLeft = false;
}
else if (pEvent.keyCode == 39)
{
keyRight = false;
}
}
// Set the velocity of the object
var speed = 4;
// And the rotation speed
var rotationSpeed = 6;
// Add an enter frame event on the moving object
myCircle.addEventListener(Event.ENTER_FRAME, circleEnterFrame);
function circleEnterFrame(pEvent)
{
// Set the default velocity to 0 if no key is pressed
var velocity = 0;
if (keyUp)
{
// If the key up is pressed set the new velocity to the speed value
velocity = speed;
}
if (keyDown)
{
// If the key down is pressed set the new velocity to the half speed value
velocity = -speed/2;
}
if (keyLeft)
{
// rotate the object
pEvent.currentTarget.rotation -= rotationSpeed;
}
if (keyRight)
{
// rotate the object
pEvent.currentTarget.rotation += rotationSpeed;
}
// Convert the degreeAngle to the radian angle
var angleRadian = pEvent.currentTarget.rotation / 180 * Math.PI;
// Move the object with the radian angle and the object speed
pEvent.currentTarget.x += Math.cos(angleRadian) * velocity;
pEvent.currentTarget.y += Math.sin(angleRadian) * velocity;
}
Any help would be very much appreciated! Thanks!

The easiest way is to do something like this:
if( roomba.hitTestObject(google)){
google.alpha = 0;
}
You'll have to check this on every frame using an ENTER_FRAME event.
If this is confusing tell me in the comments and I will clarify with more code.

Related

as3 space bar function not workingf

I have written a code to move a MovieClip on pressing space bar. So if someone presses space bar ..it activates a boolean variable from false to true and if its true the object moves ..but its not working. can some one please help. Thank you
var rope = MovieClip(this.root).boat_mc.rope_mc.fishyrope_mc.hitbox_mc;
var ropeMove:Boolean = false;
stage.addEventListener(Event.ENTER_FRAME, ropeCode);
stage.addEventListener(KeyboardEvent.KEY_UP, onSpacebarUp);
function onSpacebarUp(e:KeyboardEvent):void
{
if (e.keyCode == Keyboard.SPACE)
ropeMove = !ropeMove; // toggles ropeMove (i.e. if it's true, sets it to false, and vice versa)
}
function ropeCode(e:Event):void
{
// move the rope
if( ropeMove )
{
rope.y += xSpeed;
// stop moving if we've gone too far
if( rope.y > 600.0 )
{
rope.y = 600.0;
ropeMove = false;
}
}
}
This should work
var ropemove:Boolean = true;
var xSpeed = 5;
var once:Boolean=false;
stage.addEventListener(Event.ENTER_FRAME,ropeCode);
stage.addEventListener(KeyboardEvent.KEY_UP,onSpacebarUp);
function onSpacebarUp(e:KeyboardEvent):void
{
if (e.keyCode == 32)
{
if (ropemove==true)
{
if(once==false)
{
ropemove = false;
once=true
}
}
if(ropemove==false)
{
ropemove==true
}
}
if (rope.x >= stage.stageWidth )
{
ropemove = false;
}
trace(ropemove)
}
function ropeCode(e:Event):void
{
if (ropemove == true)
{
rope.x += xSpeed;
}
}
Two problems I can spot in your code:
1.) Everything is inside your Event.ENTER_FRAME event handler. This means every frame, that code is going to be run: including where you're adding a keyboard event listener. After 1 second, (assuming you are running at 30 fps) onSpacebarUp() will fire 30 times when you press space, and keeps increasing. Probably not a good idea, pretty sure you only want to add this once.
2.) The part where the boolean value will cause your movieclip to move is in a method: dropRope(). But this is not called anywhere, so it is actually not doing anything. Also may not need the event argument (the e:event) part, as you're not using it nor is it being called from an event.
BennettLiam's code should do something closer to what you want, I'm just adding this answer as an explanation for why your code isn't working. In their answer, they've fixed the above problems I mentioned: moved the event listener code for the keyboard outside of the event frame handler loop so it is only added once, and changed the enter frame event handler to call dropRope() o every frame, so that it is doing something.
var rope = MovieClip(this.root).boat_mc.rope_mc.fishyrope_mc.hitbox_mc;
var ropeMove:Boolean = false;
stage.addEventListener(Event.ENTER_FRAME, ropeCode);
stage.addEventListener(KeyboardEvent.KEY_UP, onSpacebarUp);
function onSpacebarUp(e:KeyboardEvent):void
{
if (e.keyCode == Keyboard.SPACE)
ropeMove = !ropeMove; // toggles ropeMove (i.e. if it's true, sets it to false, and vice versa)
}
function ropeCode(e:Event):void
{
// move the rope
if( ropeMove )
{
rope.y += xSpeed;
// stop moving if we've gone too far
if( rope.y > 600.0 )
{
rope.y = 600.0;
ropeMove = false;
}
}
}

AS3 MouseEvents

I'm doing a top-down view game. Is a really simple one in fact. The character moves when the player click in the screen. But, I have a fire button too.
I want know how I can disable the mouse from click when player press the button. Because when this happen the character moves to button spot.
Here's my code:
var walk = false;
var goX = player.x;
var goY = player.y;
var speed = 10;
var dir = "down";
stage.addEventListener(Event.ENTER_FRAME, loop);
btn.addEventListener(MouseEvent.MOUSE_DOWN, btn1);
function btn1(event:MouseEvent):void
{
fireBullet();
}
function fireBullet():void {
var playerDirection:String;
if(player.scaleX < 0){
playerDirection = "left";
} else if(player.scaleX > 0){
playerDirection = "right";
}
if(char.scaleY < 0){
playerDirection = "up";
} else if(char.scaleY > 0){
playerDirection = "down";
}
var bullet:Bullet = new Bullet(player.x, player.y, playerDirection);
stage.addChild(bullet);
}
function loop(Event)
{
if (walk == true)
{
player.w.play();
}
else
{
player.w.gotoAndStop(1);
}
player.gotoAndStop(dir);
if ((goY-speed)>player.y)
{
player.y += speed;
dir = "down";
}
else if ((goY+speed)<player.y)
{
player.y -= speed;
dir = "up";
}
if ((goX-speed)>player.x)
{
player.x += speed;
dir = "right";
}
else if ((goX+speed)<player.x)
{
player.x -= speed;
dir = "left";
}
if ((goY-speed)>player.y || (goY+speed)<player.y || (goX-speed)>player.x || (goX+speed) <player.x){
walk = true;
} else {
walk =false
}
}
stage.addEventListener(MouseEvent.CLICK, set);
function set(MouseEvent){
goX=mouseX
goY=mouseY}
Thanks.
Since mouse events bubble up the display list and you have a listener added to the stage, when the user presses a button, you need to stop the event from propagating.
In order to achieve this, in the button handler, you would need to the call stopImmediatPropagation method. So, your btn1 method would look like this:
function btn1(event:MouseEvent):void
{
fireBullet();
event.stopImmediatePropagation();
}
This way, you prevent the click event from bubbling all the way up to the stage, in turn causing the stage's click handler to be called.
Hope this helps. Have a great day.
simply, using the concept of target can be handled as follows.
try this:
function set(e:MouseEvent):void
{
var target = e.target;
//ex) if(target is MovieClip) return;
if(target is <#your fire button type#>) return;
goX=mouseX;
goY=mouseY;
}
what is different "target" vs "currentTarget"?
target: the object that fired event.
currentTarget: the object that you applied the listener to.

Continuos Timer and object for a game AS3

I am currently working on a game where you need to survive as long as possible while dodging questions that come your way. (all with AS3)
At the moment I am going from 1 scene to another in between the game field and the question field, but everytime I go to the question scene the timer in the game scene resets itself. I was wondering if it was possible to have the timer continue while being in the question scene?
Also I have a movable character in between the menus which incidentally are also made in different scenes and the player is able to move him around, and I would very much like him to stay in the last position he was in the next screen, as in I move him to the top right in the main menu and when I go to the options menu I want him to still be in the top right and not in his initial position.
As for my timer this is the code I am using at the moment:
import flash.utils.Timer;
import flash.events.Event;
import flash.events.TimerEvent;
import flash.globalization.DateTimeFormatter;
var timer:Timer = new Timer(100);
timer.start();
timer.addEventListener(TimerEvent.TIMER, timerTickHandler);
var timerCount:int = 0;
function timerTickHandler(Event:TimerEvent):void
{
timerCount += 100;
toTimeCode(timerCount);
}
function toTimeCode(milliseconds:int) : void {
//create a date object using the elapsed milliseconds
var time:Date = new Date(milliseconds);
//define minutes/seconds/mseconds
var minutes:String = String(time.minutes);
var seconds:String = String(time.seconds);
var miliseconds:String = String(Math.round(time.milliseconds)/100);
//add zero if neccecary, for example: 2:3.5 becomes 02:03.5
minutes = (minutes.length != 2) ? '0'+minutes : minutes;
seconds = (seconds.length != 2) ? '0'+seconds : seconds;
//display elapsed time on in a textfield on stage
timer_txt.text = minutes + ":" + seconds+"." + miliseconds;
}
And my character is using this code:
/* Move with Keyboard Arrows
Allows the specified symbol instance to be moved with the keyboard arrows.
Instructions:
1. To increase or decrease the amount of movement, replace the number 5 below with the number of pixels you want the symbol instance to move with each key press.
Note the number 5 appears four times in the code below.
*/
var upPressed:Boolean = false;
var downPressed:Boolean = false;
var leftPressed:Boolean = false;
var rightPressed:Boolean = false;
rutte.addEventListener(Event.ENTER_FRAME, fl_MoveInDirectionOfKey);
stage.addEventListener(KeyboardEvent.KEY_DOWN, fl_SetKeyPressed);
stage.addEventListener(KeyboardEvent.KEY_UP, fl_UnsetKeyPressed);
function fl_MoveInDirectionOfKey(event:Event)
{
if (upPressed)
{
rutte.y -= 5;
}
if (downPressed)
{
rutte.y += 5;
}
if (leftPressed)
{
rutte.x -= 5;
rutte.scaleX = 1; // face left
}
if (rightPressed)
{
rutte.x += 5;
rutte.scaleX = -1; // face right
}
}
function fl_SetKeyPressed(event:KeyboardEvent):void
{
switch (event.keyCode)
{
case Keyboard.UP:
{
upPressed = true;
break;
}
case Keyboard.DOWN:
{
downPressed = true;
break;
}
case Keyboard.LEFT:
{
leftPressed = true;
break;
}
case Keyboard.RIGHT:
{
rightPressed = true;
break;
}
}
}
function fl_UnsetKeyPressed(event:KeyboardEvent):void
{
switch (event.keyCode)
{
case Keyboard.UP:
{
upPressed = false;
break;
}
case Keyboard.DOWN:
{
downPressed = false;
break;
}
case Keyboard.LEFT:
{
leftPressed = false;
break;
}
case Keyboard.RIGHT:
{
rightPressed = false;
break;
}
Thank you in advance for all the help you can give me.
Kind Regards.
in flash there is a fundamental aspect of how timeline and scenes works. Once you move away from a frame to another frame, The content of the frame and it's properties/states/actions are gone and reseted.
Personally I recommend you use a single scene with a timeline divided into frames labeled, there you can specify a layer for the actions and global variables, one for the user interface and another one for the specific actions of each frame. example:
So you never lose the reference of variables because the frame is not constantly recreated, all your important actions, including you timer, should be in your first frame.
I was testing, here you can see a working example: http://db.tt/FZuQVvt3. Here you can download the FLA file to be used as a base for your project: http://db.tt/RHG9G5lo

How to do you get an character to jump?

This is my fist time ever needing to use this for one of my games. I want to have the character jump. I have been trying to get this result for about an hour, but with no luck =( I am using AS3, and flash CS5.5. So far all my code does is make the character go left, and right based on keyboard input. Could someone please help?
Here is my code so far:
public class Dodgeball extends MovieClip
{
public var character:Character;
public var rightDown:Boolean = false;
public var leftDown:Boolean = false;
public var speed:Number = 3;
public var timer:Timer;
public function Dodgeball()
{
character= new Character();
addChild(character);
stage.addEventListener(KeyboardEvent.KEY_DOWN, myKeyDown);
stage.addEventListener(KeyboardEvent.KEY_UP, MyKeyUp);
timer = new Timer(24);
timer.addEventListener(TimerEvent.TIMER, moveClip);
timer.start();
}
public function myKeyDown(event:KeyboardEvent):void
{
if (event.keyCode == Keyboard.RIGHT)
{
rightDown = true;
if(character.currentLabel != "walkingRight")
{
character.gotoAndStop ("walkingRight");
}
}
if (event.keyCode == Keyboard.LEFT)
{
leftDown = true;
if (character.currentLabel != "backingUp")
{
character.gotoAndStop("backingUp");
}
}
}
public function MyKeyUp(event:KeyboardEvent):void
{
if(event.keyCode == Keyboard.RIGHT)
{
character.gotoAndStop("standing");
rightDown = false;
}
if (event.keyCode == Keyboard.LEFT)
{
character.gotoAndStop("standingLeft");
leftDown = false;
}
}
public function moveClip(event:TimerEvent):void
{
if (rightDown)
{
character.x += speed;
}
if (leftDown)
{
character.x -=speed;
}
event.updateAfterEvent();
}
}
}
One method you can try is found here: http://www.actionscript.org/forums/showthread.php3?t=256009 Like your speed variable, grav determines the vertical position of the character.
var grav:Number = 10;
var jumping:Boolean = false;
var jumpPow:Number = 0;
stage.addEventListener(KeyboardEvent.KEY_DOWN, onKeyDown);
stage.addEventListener(Event.ENTER_FRAME, update);
function onKeyDown(evt:KeyboardEvent):void
{
if(evt.keyCode == Keyboard.UP)
{
if(jumping != true)
{
jumpPow = -50;
jumping = true;
}
}
}
function update(evt:Event):void
{
if(jumping)
{
player_mc.y += jumpPow;
jumpPow += grav;
if(player_mc.y >= stage.stageHeight)
{
jumping = false;
player_mc.y = stage.stageHeight;
}
}
}
Edit: Jason's method is fine, but I'm not sure if it would be useful if you plan to have some kind of collision detection.
What I would do is create a motion tween of the character jumping. then call gotoAndPlay on that frame, and on the last frame of the tween put a stop, or a gotoAndStop on the "stationary" frame, or whatever frame represents a neutral position.
if (event.keyCode == Keyboard.SHIFT)
{
character.gotoAndPlay("simpleJump");
jumpDown = false;
}
This will give you the greatest animation control over the look and feel. You could also do it programmatically, but personally, I recommend against it. It will take less time to set it up, and you can tweak and refine the jump animations later. You could make several types of jump animations based on object near the target etc.
I would also change this stuff:
if(character.currentLabel != "walkingRight")
By defining a new function where you have all the rules for when and where something can be done, so that in your control logic, you just call
if(characterCan(character,"walkright")) ...
Where characterCan(String) is a method that check if this is possible. For instance, if you are jumping and shooting, you obviously cannot walk right, so in the end, you will have to start adding pieces of logic into those if statements and it's gonna become a cluttered mess.
A very simple approach is to have a vertical speed as well as a horizontal speed.
When the user presses "UP" or "JUMP", set y speed to a negative value and update it in your movieClip function. When the character gets to a certain height, reverse the speed.
Using gravity and acceleration looks better but this is a really good place to start. Look into kinematic equations to see how you would make the character accelerate.
public var originalY;
public function myKeyDown(event:KeyboardEvent):void
{
if (event.keyCode == Keyboard.UP && vSpeed == 0)
{
originalY = character.y;
ySpeed = -1;
}
}
public function moveClip(event:TimerEvent):void
{
if (vSpeed != 0)
{
character.y += vSpeed;
/* make the character fall down after reaching max jump height */
if(originalY - character.y > jumpHeight) {
vSpeed = vSpeed * -1;
}
/* level the character after he's hit the ground (so he doesn't go through) */
else if(character.y >= originalY) {
character.y = originalY;
vSpeed = 0;
}
}
}

AS3 Stop character from moving through walls

I want to stop the movieclips movement when it hits a wall (another movieclip).
The example below works, but after the collision the movieclip 'blocks' all movement to the left...
My question to you is, is this a good way and why isn't it working well?
There will be something wrong in this code, but i'm learning.
For now the example with the leftArrow key;
variables to check the key, if it's hitting the walls and if it's moving or not:
var leftArrow:Boolean;
var speed:int = 10;
var hitting:Boolean;
var ismoving:Boolean;
event listeners for the keys/movement and detecting collision:
stage.addEventListener(KeyboardEvent.KEY_DOWN, keyPressed);
stage.addEventListener(KeyboardEvent.KEY_UP, keyReleased);
stage.addEventListener(Event.ENTER_FRAME, walking);
stage.addEventListener(Event.ENTER_FRAME, detectHit);
detecting collision function:
function detectHit(e:Event) :void
{
if(char.hitTestObject(bounds))
{
hitting = true;
}
}
function to the left arrow key:
function keyPressed(event:KeyboardEvent):void
{
if (event.keyCode == Keyboard.LEFT)
{
leftArrow = true;
}
}
function keyReleased(event:KeyboardEvent):void
{
if (event.keyCode == Keyboard.LEFT)
{
leftArrow = false;
}
}
And the reason it's not working is probably here, but I don't understand why not:
function walking(event:Event):void {
if (rightArrow) {
char.x += speed;
}
if (leftArrow && ! hitting) {
char.x -= speed;
}
else
{
ismoving = false
}
if (leftArrow && ! hitting)
char will move if hitting is false. When char.hitTestObject(bounds) is true you are setting hitting to true. You are not setting hitting again to false anywhere. That's why once left wall is hit it stops left movement permanently. You need to figure out suitable condition to set hitting to false again.
Adding an else branch in detectHit should solve the problem.
function detectHit(e:Event):void {
if(char.hitTestObject(bounds))
{
hitting = true;
} else {
hitting = false; // add this
}
}
Allthough Taskinoor's method should work, I would suggest another way to do your hittests.
Since you probably are creating a game (character and bounds), you will have more than one bound. In that case, I would strongly suggest bitmap-hittesting. This way, you can create all your bounds in one movieclip and test for a hit.
I will explain this by using the example of a maze. The maze would then be some lines in a movieclip, randomly put together. If you use HitTestObject and you aren't hitting one of the lines, but your character is over the movieclip, hitTestObject will return true, even though you are not hitting a wall. By using bitmapHitTesting, you can overcome this problem (BitmapHitTest takes transparant pixels into account, whereas hitTestObject does not).
Below you can find an example of how to do bitmapHitTesting. Creating the bitmaps in this function is not necesarry if they do not change shape. In that case, I would suggest placing the code for the bitmapdata in a added_to_stage-method.
private var _previousX:int;
private var _previousY:int;
private var _bmpd:BitmapData ;
private var _physicalBitmapData:BitmapData;
private function walkAround(e:Event):void
{
var _xTo:int = //Calculate x-to-position;
var _yTo:int = //Calculate y-to-position;
//If your character doesn't change shape, you don't have to recalculate this bitmapData over and over.
//I suggest placing it in a ADDED_TO_STAGE-Event in that case.
_bmpd = new BitmapData(char.width, char.height, true, 0);
_bmpd.draw(char);
//If your bounds are static, you don't have to recalculate this bitmapData over and over.
//I suggest placing it in a ADDED_TO_STAGE-Event in that case.
_physicalBitmapData = new BitmapData(bounds.width, bounds.height, true, 0);
_bmpd.draw(bounds);
//The below line is the actual hittest
if(_physicalBitmapData.hitTest(new Point(0, 0), 255, _bmpd, new Point(char.x, char.y), 255))
{
char.x = _previousX;
char.y = _previousY;
}
else
{
char.x = _xTo;
char.y = _yTo;
}
_previousX = char.x;
_previousY = char.y;
}
Look at my hint,
function loop(Event)
{
if(isHit==false)
{
if(isRight==true){head_mc.x+=1}
if(isLeft==true){head_mc.x-=1}
if(isUp==true){head_mc.y-=1}
if(isDown==true){head_mc.y+=1}
}
if(head_mc.hitTestObject(build_mc))
{
isHit=true;
if(isRight==true){head_mc.x-=1}
if(isLeft==true){head_mc.x+=1}
if(isUp==true){head_mc.y+=1}
if(isDown==true){head_mc.y-=1}
}
else
{
isHit=false;
}
}
I use step back to opposite direction instead.