How to edit the image before upload (i.e make circle, square, effects, etc.).
Below I have used Krajee FileInput widget, how do I edit my image before upload?
<?php
echo $form->field($model, 'imagefile')
->widget(FileInput::classname(), [
'options'=>['multiple'=>false]
]);
?>
you can edit image after image upload from controller
$imgData = UploadedFile::getInstance($model, 'photo');
$photo = resize_image($imgData, 400, 400);
by using this model:
<?php
namespace backend\models;
Class Resize
{
// *** Class variables
private $image;
private $width;
private $height;
private $imageResized;
function __construct($fileName)
{
// *** Open up the file
$this->image = $this->openImage($fileName);
// *** Get width and height
$this->width = imagesx($this->image);
$this->height = imagesy($this->image);
}
private function openImage($file)
{
// *** Get extension
$extension = strtolower(strrchr($file, '.'));
switch($extension)
{
case '.jpg':
case '.jpeg':
$img = imagecreatefromjpeg($file);
break;
case '.gif':
$img = imagecreatefromgif($file);
break;
case '.png':
$img = imagecreatefrompng($file);
break;
default:
$img = false;
break;
}
return $img;
}
public function resizeImage($newWidth, $newHeight, $option="auto")
{
// *** Get optimal width and height - based on $option
$optionArray = $this->getDimensions($newWidth, $newHeight, strtolower($option));
$optimalWidth = $optionArray['optimalWidth'];
$optimalHeight = $optionArray['optimalHeight'];
// *** Resample - create image canvas of x, y size
$this->imageResized = imagecreatetruecolor($optimalWidth, $optimalHeight);
imagecopyresampled($this->imageResized, $this->image, 0, 0, 0, 0, $optimalWidth, $optimalHeight, $this->width, $this->height);
// *** if option is 'crop', then crop too
if ($option == 'crop') {
$this->crop($optimalWidth, $optimalHeight, $newWidth, $newHeight);
}
}
private function getDimensions($newWidth, $newHeight, $option)
{
switch ($option)
{
case 'exact':
$optimalWidth = $newWidth;
$optimalHeight= $newHeight;
break;
case 'portrait':
$optimalWidth = $this->getSizeByFixedHeight($newHeight);
$optimalHeight= $newHeight;
break;
case 'landscape':
$optimalWidth = $newWidth;
$optimalHeight= $this->getSizeByFixedWidth($newWidth);
break;
case 'auto':
$optionArray = $this->getSizeByAuto($newWidth, $newHeight);
$optimalWidth = $optionArray['optimalWidth'];
$optimalHeight = $optionArray['optimalHeight'];
break;
case 'crop':
$optionArray = $this->getOptimalCrop($newWidth, $newHeight);
$optimalWidth = $optionArray['optimalWidth'];
$optimalHeight = $optionArray['optimalHeight'];
break;
}
return array('optimalWidth' => $optimalWidth, 'optimalHeight' => $optimalHeight);
}
private function getSizeByFixedHeight($newHeight)
{
$ratio = $this->width / $this->height;
$newWidth = $newHeight * $ratio;
return $newWidth;
}
private function getSizeByFixedWidth($newWidth)
{
$ratio = $this->height / $this->width;
$newHeight = $newWidth * $ratio;
return $newHeight;
}
private function getSizeByAuto($newWidth, $newHeight)
{
if ($this->height < $this->width)
// *** Image to be resized is wider (landscape)
{
$optimalWidth = $newWidth;
$optimalHeight= $this->getSizeByFixedWidth($newWidth);
}
elseif ($this->height > $this->width)
// *** Image to be resized is taller (portrait)
{
$optimalWidth = $this->getSizeByFixedHeight($newHeight);
$optimalHeight= $newHeight;
}
else
// *** Image to be resizerd is a square
{
if ($newHeight < $newWidth) {
$optimalWidth = $newWidth;
$optimalHeight= $this->getSizeByFixedWidth($newWidth);
} else if ($newHeight > $newWidth) {
$optimalWidth = $this->getSizeByFixedHeight($newHeight);
$optimalHeight= $newHeight;
} else {
// *** Sqaure being resized to a square
$optimalWidth = $newWidth;
$optimalHeight= $newHeight;
}
}
return array('optimalWidth' => $optimalWidth, 'optimalHeight' => $optimalHeight);
}
private function getOptimalCrop($newWidth, $newHeight)
{
$heightRatio = $this->height / $newHeight;
$widthRatio = $this->width / $newWidth;
if ($heightRatio < $widthRatio) {
$optimalRatio = $heightRatio;
} else {
$optimalRatio = $widthRatio;
}
$optimalHeight = $this->height / $optimalRatio;
$optimalWidth = $this->width / $optimalRatio;
return array('optimalWidth' => $optimalWidth, 'optimalHeight' => $optimalHeight);
}
private function crop($optimalWidth, $optimalHeight, $newWidth, $newHeight)
{
// *** Find center - this will be used for the crop
$cropStartX = ( $optimalWidth / 2) - ( $newWidth /2 );
$cropStartY = ( $optimalHeight/ 2) - ( $newHeight/2 );
$crop = $this->imageResized;
//imagedestroy($this->imageResized);
// *** Now crop from center to exact requested size
$this->imageResized = imagecreatetruecolor($newWidth , $newHeight);
imagecopyresampled($this->imageResized, $crop , 0, 0, $cropStartX, $cropStartY, $newWidth, $newHeight , $newWidth, $newHeight);
}
public function saveImage($savePath, $imageQuality="100")
{
// *** Get extension
$extension = strrchr($savePath, '.');
$extension = strtolower($extension);
switch($extension)
{
case '.jpg':
case '.jpeg':
if (imagetypes() & IMG_JPG) {
imagejpeg($this->imageResized, $savePath, $imageQuality);
}
break;
case '.gif':
if (imagetypes() & IMG_GIF) {
imagegif($this->imageResized, $savePath);
}
break;
case '.png':
// *** Scale quality from 0-100 to 0-9
$scaleQuality = round(($imageQuality/100) * 9);
// *** Invert quality setting as 0 is best, not 9
$invertScaleQuality = 9 - $scaleQuality;
if (imagetypes() & IMG_PNG) {
imagepng($this->imageResized, $savePath, $invertScaleQuality);
}
break;
// ... etc
default:
// *** No extension - No save.
break;
}
imagedestroy($this->imageResized);
}
}
?>
Related
am trying to add a new feature to a Scrabble project on Angular.
The feature is to swicth the places of the bonus case randomly , when user activate this feature.
my problem is that it's always activated , tried usin boolean or number always same problem .
can someone tell me what am i doing wrong please.
doc.html
<button (click)="activeRandomBonus()" class="btn btn-default form-control increaseBtn">Activer BONUS</button>
component.ts
#Component({
selector: 'app-param-game',
templateUrl: './param-game.component.html',
styleUrls: ['./param-game.component.scss'],
})
export class ParamGameComponent {
timeMax: number = 240;
timeMin: number = 0;
gridTile: GridTile;
console: Console;
textShow: boolean;
constructor(
public paramGameService: ParamGameService,
private dialogRef: MatDialogRef<ParamGameComponent>,
public dialog: MatDialog
) { }
// activeRandomBonus(): void {
// this.gridTile.randomButton();
// }
}
grid-tile.ts
export class GridTile {
arrayOps: ArrayOperations = new ArrayOperations();
paramGameService: ParamGameService = new ParamGameService();
letter: string;
bonusName: string;
// **test: number;**
isJoker: boolean = false;
multiplier: defaults.Multipliers = defaults.Multipliers.NoMultiplier;
pos: Vec2 = {
x: 0,
y: 0,
};
gridContext: CanvasRenderingContext2D;
constructor(context: CanvasRenderingContext2D, x: number, y: number) {
this.letter = '';
this.gridContext = context;
this.pos.x = x;
this.pos.y = y;
if (this.arrayOps.containsCoordinates(this.pos, defaults.MULTIPLIER_3W)) {
this.multiplier = 5;
} else if (this.arrayOps.containsCoordinates(this.pos, defaults.MULTIPLIER_2W)) {
this.multiplier = 4;
} else if (this.arrayOps.containsCoordinates(this.pos, defaults.MULTIPLIER_3L)) {
this.multiplier = 3;
} else if (this.arrayOps.containsCoordinates(this.pos, defaults.MULTIPLIER_2L)) {
this.multiplier = 2;
} else if (this.arrayOps.containsCoordinates(this.pos, defaults.STARTING_TILE)) {
this.multiplier = 0;
}
}
idOfTile(word1: string, word2: string) {
this.gridContext.fillText(
word1,
this.pos.x * defaults.TILE_SIZE + defaults.TILE_SIZE / 2 - defaults.TEN,
this.pos.y * defaults.TILE_SIZE + defaults.TILE_SIZE / 2,
);
this.gridContext.fillText(
word2,
this.pos.x * defaults.TILE_SIZE + defaults.TILE_SIZE / 2 - defaults.EIGHT,
this.pos.y * defaults.TILE_SIZE + defaults.TILE_SIZE / 2 + defaults.TWELVE,
);
}
randBonusName(x = Math.floor(Math.random() * 5)) {
if (x === 1 || x === 3) return (this.bonusName = 'Triple');
else return (this.bonusName = 'Double');
}
randomButton(): void {
this.test = +1;
// window.location.reload();
}
drawTile() {
// draw empty tile
this.gridContext.strokeRect(
this.pos.x * defaults.TILE_SIZE,
this.pos.y * defaults.TILE_SIZE,
defaults.PLAY_AREA_DEFAULT_WIDTH / defaults.TILES_NUMBER,
defaults.PLAY_AREA_DEFAULT_HEIGHT / defaults.TILES_NUMBER,
);
// Background style depends on multiplier
this.gridContext.fillStyle = 'white';
switch (this.multiplier) {
case defaults.Multipliers.ThreeW: {
this.gridContext.fillStyle = 'red';
break;
}
case defaults.Multipliers.TwoW: {
this.gridContext.fillStyle = 'pink';
break;
}
case defaults.Multipliers.ThreeL: {
this.gridContext.fillStyle = 'blue';
break;
}
case defaults.Multipliers.TwoL: {
this.gridContext.fillStyle = 'cyan';
break;
}
case defaults.Multipliers.Center: {
this.gridContext.fillStyle = 'green';
break;
}
case defaults.Multipliers.NoMultiplier: {
this.gridContext.fillStyle = 'white';
break;
}
// No default
}
this.gridContext.fillRect(
this.pos.x * defaults.TILE_SIZE + this.gridContext.lineWidth - 1,
this.pos.y * defaults.TILE_SIZE + this.gridContext.lineWidth - 1,
defaults.PLAY_AREA_DEFAULT_WIDTH / defaults.TILES_NUMBER - this.gridContext.lineWidth,
defaults.PLAY_AREA_DEFAULT_HEIGHT / defaults.TILES_NUMBER - this.gridContext.lineWidth,
);
this.gridContext.fillStyle = 'black';
this.gridContext.font = '10px Roboto';
switch (this.multiplier) {
case defaults.Multipliers.ThreeW: {
if (this.test <= 0) this.idOfTile('Mot', 'Triple');
//desactive random bonus
else this.idOfTile('Mot', this.randBonusName()); //active random bonus
break;
}
case defaults.Multipliers.TwoW: {
if (this.test <= 0) {
this.idOfTile('Mot', 'Double');
} else this.idOfTile('Mot', this.randBonusName());
break;
}
case defaults.Multipliers.ThreeL: {
if (this.test === 0) {
this.idOfTile('Lettre', 'Triple');
} else this.idOfTile('Lettre', this.randBonusName());
break;
}
case defaults.Multipliers.TwoL: {
if (this.test === 0) {
this.idOfTile('Lettre', 'Double');
} else this.idOfTile('Lettre', this.randBonusName());
break;
}
case defaults.Multipliers.Center: {
this.gridContext.fillText(
'Start',
this.pos.x * defaults.TILE_SIZE + defaults.TILE_SIZE / 2 - defaults.TEN,
this.pos.y * defaults.TILE_SIZE + defaults.TILE_SIZE / 2 + defaults.EIGHT,
);
break;
}
case defaults.Multipliers.NoMultiplier: {
// do nothing
break;
}
// No default
}
}
drawLetter(letter: string, isJoker: boolean) {
if (!this.gridContext) {
this.letter = letter;
return;
}
this.gridContext.fillStyle = 'peru';
this.gridContext.fillRect(
this.pos.x * defaults.TILE_SIZE + this.gridContext.lineWidth,
this.pos.y * defaults.TILE_SIZE + this.gridContext.lineWidth,
defaults.PLAY_AREA_DEFAULT_WIDTH / defaults.TILES_NUMBER - this.gridContext.lineWidth - 2,
defaults.PLAY_AREA_DEFAULT_HEIGHT / defaults.TILES_NUMBER - this.gridContext.lineWidth - 2,
);
// draw letter
this.gridContext.fillStyle = 'black';
this.gridContext.font = '25px Arial';
this.gridContext.fillText(
letter,
this.pos.x * defaults.TILE_SIZE + defaults.TILE_SIZE / 2 - defaults.TEN,
this.pos.y * defaults.TILE_SIZE + defaults.TILE_SIZE / 2 + defaults.EIGHT,
);
const scoreString = isJoker ? '0' : (defaults.LETTER_VALUES.get(letter) ?? 1)?.toString();
this.isJoker = isJoker;
// draw letter score
this.gridContext.font = '15px Arial';
// TODO: take2 digit scores into account
this.gridContext.fillText(
scoreString,
this.pos.x * defaults.TILE_SIZE + defaults.TILE_SIZE - defaults.TWELVE,
this.pos.y * defaults.TILE_SIZE + defaults.TILE_SIZE - defaults.FOUR,
);
this.letter = letter; // saving the letter
}
get tileLetter(): string {
return this.letter;
}
}
it looks like you are only setting the random feature to on, but when you click the button it doesnt check the current stat. You can do this fairly easily with boolean values by setting them to the opposite of what the currently are.
active = false;
randomButton(): void {
this.active = !this.active;
}
not sure how your code works but you may also need to trigger the class to refresh the logic.
active = false;
randomButton(): void {
this.active = !this.active;
this.drawTile();
}
I am getting this error :
ReferenceError: Error #1065: Variable addFrameScript is not defined.
at survival()
I'm having the problem when I run this code :
package {
import flash.display.Sprite;
import flash.events.Event;
import flash.events.KeyboardEvent;
import flash.display.*;
import flash.media.SoundMixer;
import flash.media.SoundTransform;
public class survival extends Sprite {
public var ground:ground_mc = new ground_mc();
public var environment:environment_mc = new environment_mc();
public var player:player_mc = new player_mc();
public var monster:monster_mc = new monster_mc();
public var light:Sprite=new Sprite ;
public var battery:battery_mc = new battery_mc();
public var key_pressed:int=0;
public var radius:int=8;
public var player_speed:int=2;
public var monster_speed:int=1;
public var torch_power:int=150;
public var torch_step:int = 100;
public var torch_angle:int=60;
public var torch_angle_step:int=35;
public var up,down,left,right:Boolean=false;
public var flicker=0;
public var count:int;
public var sec:int;
public var torchBattery:int = 100;
var topLeft:Boolean = true;
var topRight:Boolean = false;
var bottomLeft:Boolean = false;
var bottomRight:Boolean = false;
public function survival():void {
addChild(ground);
addChild(environment);
addChild(light);
addChild(player);
addChild (battery);
addChild(monster);
player.x=250;
player.y=200;
battery.x=321;
battery.y=29;
environment.y = 0;
environment.x = 0;
ground.mask=light;
addEventListener(Event.ENTER_FRAME,on_enter_frame);
addEventListener(Event.ENTER_FRAME,on_enter_frame2);
stage.addEventListener(KeyboardEvent.KEY_DOWN, on_key_down);
stage.addEventListener(KeyboardEvent.KEY_UP, on_key_up);
}
public function on_enter_frame(e:Event):void {
if (up) {
environment.y+=player_speed;
ground.y+=player_speed;
monster.y+=player_speed;
}
if (down) {
environment.y-=player_speed;
ground.y-=player_speed;
monster.y-=player_speed;
}
if (left) {
environment.x+=player_speed;
ground.x+=player_speed;
monster.x+=player_speed;
}
if (right) {
environment.x-=player_speed;
ground.x-=player_speed;
monster.x-=player_speed;
}
if (environment.collisions.hitTestPoint(player.x, player.y+radius, true)) {
environment.y+=player_speed;
ground.y+=player_speed;
monster.y+=player_speed;
}
if (environment.collisions.hitTestPoint(player.x, player.y-radius, true)) {
environment.y-= player_speed;
ground.y-= player_speed;
monster.y-= player_speed;
}
if (environment.collisions.hitTestPoint(player.x-radius, player.y, true)) {
environment.x-= player_speed;
ground.x-= player_speed;
monster.x-= player_speed;
}
if (environment.collisions.hitTestPoint(player.x+radius, player.y, true)) {
environment.x+= player_speed;
ground.x+= player_speed;
monster.x+= player_speed;
}
var dist_x:Number=player.x-mouseX;
var dist_y:Number=player.y-mouseY;
var angle:Number=- Math.atan2(dist_x,dist_y);
player.rotation=to_degrees(angle);
light.graphics.clear();
if (Math.random()*100>flicker) {
light.graphics.beginFill(0xffffff, 100);
light.graphics.moveTo(player.x, player.y);
for (var i:int=0; i<=torch_angle; i+=(torch_angle/torch_angle_step)) {
ray_angle = to_radians((to_degrees(angle)-90-(torch_angle/2)+i));
for (var j:int=1; j<=torch_step; j++) {
if (environment.collisions.hitTestPoint(player.x+(torch_power/torch_step*j)*Math.cos(ray_angle), player.y+(torch_power/torch_step*j)*Math.sin(ray_angle), true)) {
break;
}
}
light.graphics.lineTo(player.x+(torch_power/torch_step*j)*Math.cos(ray_angle), player.y+(torch_power/torch_step*j)*Math.sin(ray_angle));
}
light.graphics.lineTo(player.x, player.y);
light.graphics.endFill();
}
if (torchBattery > 0) {
count += 1;
if (count >= 30) {
count = 0;
sec += 1;
}
if (sec >= 2) {
sec = 0;
flicker += 1;
torchBattery -= 1;
changeMovement();
}
}
battery.battery.text = "Torch Battery: " + torchBattery + "%";
var theDistance:Number = distance(monster.x, player.x, monster.y, player.y);
var myVolume:Number = 2-(0.004* theDistance);
var Volume:Number = myVolume;
if (Volume < 0) {
Volume = 0;
}
SoundMixer.soundTransform = new SoundTransform(Volume);
trace(theDistance);
if (distance < 100) {
removeEventListener(Event.ENTER_FRAME,on_enter_frame);
removeEventListener(Event.ENTER_FRAME,on_enter_frame2);
stage.removeEventListener(KeyboardEvent.KEY_DOWN, on_key_down);
stage.removeEventListener(KeyboardEvent.KEY_UP, on_key_up);
removeChild(ground);
removeChild(environment);
removeChild(light);
removeChild(player);
removeChild (battery);
removeChild(monster);
gotoAndStop(2);
}
}
function on_enter_frame2 (e:Event) :void {
if (environment.collisions.hitTestPoint(monster.x, monster.y+radius, true)) {
monster.y -= monster_speed;
}
if (environment.collisions.hitTestPoint(monster.x,monster.y-radius, true)) {
monster.y += monster_speed;
}
if (environment.collisions.hitTestPoint(monster.x-radius, monster.y, true)) {
monster.x+=monster_speed;
}
if (environment.collisions.hitTestPoint(monster.x+radius, monster.y, true)) {
monster.x -= monster_speed;
}
if (topLeft) {
monster.x -= monster_speed;
monster.y -= monster_speed;
} else if (topRight) {
monster.x += monster_speed;
monster.y -= monster_speed;
} else if (bottomLeft) {
monster.x -= monster_speed;
monster.y += monster_speed;
} else if (bottomRight) {
monster.x += monster_speed;
monster.y += monster_speed;
}
}
function changeMovement():void {
var die2:Number = Math.floor(Math.random()*4);
if (die2 == 1) {
topLeft = true;
topRight = false;
bottomLeft = false;
bottomRight = false;
}
if (die2 == 2) {
topLeft = false;
topRight = true;
bottomLeft = false;
bottomRight = false;
}
if (die2 == 3) {
topLeft = false;
topRight = false;
bottomLeft = true;
bottomRight = false;
}
if (die2 == 4) {
topLeft = false;
topRight = false;
bottomLeft = false;
bottomRight = true;
}
}
public function on_key_down(e:KeyboardEvent):void {
switch (e.keyCode) {
case 37 :
left=true;
break;
case 38 :
up=true;
break;
case 39 :
right=true;
break;
case 40 :
down=true;
break;
/*case 49 :
torch_power++;
break;
case 50 :
torch_power--;
break;*/
}
}
public function on_key_up(e:KeyboardEvent):void {
switch (e.keyCode) {
case 37 :
left=false;
break;
case 38 :
up=false;
break;
case 39 :
right=false;
break;
case 40 :
down=false;
break;
}
}
public function to_radians(n:Number):Number {
return (n*0.0174532925);
}
public function to_degrees(n:Number):Number {
return (n*57.2957795);
}
function distance(x1:Number, x2:Number, y1:Number, y2:Number): Number {
var dx:Number = x1-x2;
var dy:Number = y1-y2;
return Math.sqrt(dx * dx + dy * dy);
}
}
}
On my timeline I have a blank keyframe with the sound effect of a music box playing, and a second frame with the animated jumpscare. The game is that you're in a bird's eye view of a person with a torch walking through a maze. The 'monster' moves around the maze and you must stay away from it. As it gets closer, the music box that is playing will get louder. Also, your torch only has a certain amount of battery. As the battery reduces, the torch will flicker more untill it eventually stops working. It worcked fine until I tried to make the jumpscare. This is all the coding in the game.
In the 'Compiler Errors' it also states:
/Users/ethan/Documents/Flash Stuff/Flash Stuff [from macbook]/survival/survival.as, Line 164 Warning: 1060: Migration issue: The method gotoAndStop is no longer supported. For more information, see MovieClip.gotoAndStop()..
Any suggestions or help I'll be very grateful.
Sprite Class doesn't have gotoAndStop method. This method implemented only in MovieClip class. So, you should replace
public class survival extends Sprite {
with
public class survival extends MovieClip {
The way I've done the run in my game is it detects you clicked the run button which is a Movieclip, then it set the increased walkspeeds. If you lift your finger, or move it off the button, it reverts it back the default walkspeed is.
So, the problem is the run button only works when pressed prior to the directional DPAD.
How do I fix this?
My movement class
package
{
import flash.display.Stage;
import flash.display.MovieClip;
import flash.events.Event;
import flash.events.TouchEvent;
import flash.net.dns.AAAARecord;
import flash.ui.Multitouch;
import flash.ui.MultitouchInputMode;
public class Movement extends MovieClip
{
public function Movement(main:Game)
{
trace("SUCCESS | Constructed Movement Class");
addChild(Game.playerPosKeeper_mc);
Game.playerPosKeeper_mc.x = 384;
Game.playerPosKeeper_mc.y = 46;
addChild(main.up_dpad);
main.up_dpad.x = 55;
main.up_dpad.y = 336;
addChild(main.down_dpad);
main.down_dpad.x = 57;
main.down_dpad.y = 432;
addChild(main.left_dpad);
main.left_dpad.x = 19;
main.left_dpad.y = 372;
addChild(main.right_dpad);
main.right_dpad.x = 118;
main.right_dpad.y = 372;
addChild(main.menu_dpad);
main.menu_dpad.x = 61;
main.menu_dpad.y = 377;
addChild(main.run_dpad);
main.run_dpad.x = 684;
main.run_dpad.y = 369;
addChild(main.barrierRoof1_game);
main.barrierRoof1_game.x = 0;
main.barrierRoof1_game.y = 0;
addChild(main.barrierRoof2_game);
main.barrierRoof2_game.x = 0;
main.barrierRoof2_game.y = 470;
addChild(main.barrierRoof3_game);
main.barrierRoof3_game.x = 0;
main.barrierRoof3_game.y = 320;
addChild(main.barrierSide1_game);
main.barrierSide1_game.x = 0;
main.barrierSide1_game.y = 0;
addChild(main.barrierSide2_game);
main.barrierSide2_game.x = 790;
main.barrierSide2_game.y = 0;
Multitouch.inputMode = MultitouchInputMode.TOUCH_POINT;
main.run_dpad.addEventListener(TouchEvent.TOUCH_BEGIN, onTouchBeginRUN);
main.run_dpad.addEventListener(TouchEvent.TOUCH_OUT, onTouchEndRUN);
main.run_dpad.addEventListener(TouchEvent.TOUCH_END, onTouchEndRUN);
function onTouchBeginRUN(e:TouchEvent):void
{
Game.upWalkspeed = -5;
Game.downWalkspeed = 5;
Game.leftWalkspeed = -5;
Game.rightWalkspeed = 5;
}
function onTouchEndRUN(e:TouchEvent):void
{
Game.upWalkspeed = -3;
Game.downWalkspeed = 3;
Game.leftWalkspeed = -3;
Game.rightWalkspeed = 3;
}
for each (var aButton:MovieClip in main.Buttons)
{
aButton.addEventListener(TouchEvent.TOUCH_BEGIN, onDown);
aButton.addEventListener(TouchEvent.TOUCH_OUT, onUp);
aButton.addEventListener(TouchEvent.TOUCH_END, onUp);
}
function onDown(e:TouchEvent):void
{
switch (e.currentTarget)
{
case main.up_dpad :
Game.goingUp = true;
Game.goingDown = false;
Game.goingLeft = false;
Game.goingRight = false;
main._Direction.x = 0;
main._Direction.y = Game.upWalkspeed;
if (Game.player1)
{
if (P1UAnim_mc != null)
{
}
else
{
var P1UAnim_mc:MovieClip = new mc_P1UAnim();
addChild(P1UAnim_mc);
}
}
else if (Game.player2)
{
if (P2UAnim_mc != null)
{
}
else
{
var P2UAnim_mc:MovieClip = new mc_P2UAnim();
addChild(P2UAnim_mc);
}
}
break;
case main.down_dpad :
Game.goingUp = false;
Game.goingDown = true;
Game.goingLeft = false;
Game.goingRight = false;
main._Direction.x = 0;
main._Direction.y = Game.downWalkspeed;
if (Game.player1)
{
if (P1DAnim_mc != null)
{
}
else
{
var P1DAnim_mc:MovieClip = new mc_P1DAnim();
addChild(P1DAnim_mc);
}
}
else if (Game.player2)
{
if (P2DAnim_mc != null)
{
}
else
{
var P2DAnim_mc:MovieClip = new mc_P2DAnim();
addChild(P2DAnim_mc);
}
}
break;
case main.left_dpad :
Game.goingUp = false;
Game.goingDown = false;
Game.goingLeft = true;
Game.goingRight = false;
main._Direction.x = Game.leftWalkspeed;
main._Direction.y = 0;
if (Game.player1)
{
if (P1LAnim_mc != null)
{
}
else
{
var P1LAnim_mc:MovieClip = new mc_P1LAnim();
addChild(P1LAnim_mc);
}
}
else if (Game.player2)
{
if (P2LAnim_mc != null)
{
}
else
{
var P2LAnim_mc:MovieClip = new mc_P2LAnim();
addChild(P2LAnim_mc);
}
}
break;
case main.right_dpad :
Game.goingUp = false;
Game.goingDown = false;
Game.goingLeft = false;
Game.goingRight = true;
main._Direction.x = Game.rightWalkspeed;
main._Direction.y = 0;
if (Game.player1)
{
if (P1RAnim_mc != null)
{
}
else
{
var P1RAnim_mc:MovieClip = new mc_P1RAnim();
addChild(P1RAnim_mc);
}
}
else if (Game.player2)
{
if (P2RAnim_mc != null)
{
}
else
{
var P2RAnim_mc:MovieClip = new mc_P2RAnim();
addChild(P2RAnim_mc);
}
}
break;
}
if (! Game.inMotion)
{
Game.inMotion = true;
addEventListener(Event.ENTER_FRAME, onFrame);
}
}
function onFrame(e:Event)
{
movePlayer(main._Direction.x, main._Direction.y);
}
function onUp(e:TouchEvent):void
{
removeEventListener(Event.ENTER_FRAME, onFrame);
Game.goingUp = false;
Game.goingDown = false;
Game.goingLeft = false;
Game.goingRight = false;
Game.inMotion = false;
main._Direction.x = 0;
main._Direction.y = 0;
}
function movePlayer(movementX:Number, movementY:Number):void
{
var originalX:Number = Game.playerPosKeeper_mc.x;
var originalY:Number = Game.playerPosKeeper_mc.y;
Game.playerPosKeeper_mc.x += movementX;
if (checkCollision())
{
Game.playerPosKeeper_mc.x = originalX;
}
Game.playerPosKeeper_mc.y += movementY;
if (checkCollision())
{
Game.playerPosKeeper_mc.y = originalY;
}
}
function checkCollision():Boolean
{
for each (var StageCollisions:MovieClip in main.StageCollisions)
{
if (Game.playerPosKeeper_mc.hitTestObject(StageCollisions))
{
return true;
Game.inMotion = false;
}
}
return false;
}
}
}
}
EDIT:
Here's how I have done movement:
There is a movieclip thats binded to the coordinates of the player. This is what animations set their x and y coordinates to.
If a player starts moving, then an inMotion variable becomes true, and this means the player is moving.
A variable of the direction the player is going in also will change (if he's moving left goingLeft = true)
If the player hits something, or lets go of a direction on the DPAD, then inMotion is false.
This is done so that animations can be added to the stage at appropriate times, and be animated at appropriate times.
For example:
I press left DPAD
inMotion = true, goingLeft = true
If the left animation is not on the stage, add it to the stage.
left animation detects variables are responds to them accordingly:
inMotion && goingLeft
move left direction
!inMotion && !goingLeft
were idle then, do not animate
inMotion && !goingLeft
were moving in another direction, remove the animation
I press right DPAD
follows the same cycle mentioned above
This ensures the right animation is played at the correc times, and this code probably is longer than
it needs to be, but this is honestly shows the limits to what I know in code.
As soon as you see 2 blocks of code that look similar, know that code is bad: https://en.wikipedia.org/wiki/Duplicate_code. The formula less code = better is always right.
Empty blocks of code reduce readability:
// Bad.
if (condition)
{
}
else
{
// some code
}
// Good.
if (!condition)
{
// some code
}
You can also stack several conditions into one if case with logical and && and logical or || unless it becomes unreadable:
// Bad.
if (conditiona)
{
if (conditionb)
{
if (conditionc)
{
}
else
{
// some code
}
}
}
// Better.
if (conditiona && conditionb && !conditionc)
{
// some code
}
If your aim is to assign a single variable, instead of barrage of ifs you can use a ternar operator. Again, unless readability drops:
var foo:*;
// Block of ifs.
if (conditiona)
{
foo = 1;
}
else if (conditionb)
{
foo = 2;
}
// Ternar assignment.
var foo:* = conditiona? 1: conditionb? 2: foo;
// Ternar assignment in a more readable form.
var foo:* = conditiona? 1: (conditionb? 2: foo);
So, your code with all of above applied:
function setDirection(tox:Number, toy:Number):void
{
Game.goingUp = (toy < 0);
Game.goingDown = (toy > 0);
Game.goingLeft = (tox < 0);
Game.goingRight = (tox > 0);
main._Direction.y = Game.goingUp ? Game.upWalkspeed : Game.goingDown ? Game.downWalkspeed : 0;
main._Direction.x = Game.goingLeft? Game.leftWalkspeed: Game.goingRight? Game.rightWalkspeed: 0;
}
function onDown(e:TouchEvent):void
{
if (Game.player1 && !P1UAnim_mc)
{
var P1UAnim_mc:MovieClip = new mc_P1UAnim();
addChild(P1UAnim_mc);
}
if (Game.player2 && !P2UAnim_mc)
{
var P2UAnim_mc:MovieClip = new mc_P2UAnim();
addChild(P2UAnim_mc);
}
switch (e.currentTarget)
{
case main.up_dpad :
setDirection(0,-1);
break;
case main.down_dpad :
setDirection(0,1);
break;
case main.left_dpad :
setDirection(-1,0);
break;
case main.right_dpad :
setDirection(1,0);
break;
}
if (!Game.inMotion)
{
Game.inMotion = true;
addEventListener(Event.ENTER_FRAME, onFrame);
}
}
You can additionally spare yourself of programming UI layout by designing UI in Flash IDE (Animate or CS6 or whichever you have there). You design MovieClip in Library so that it has all interfaces you need in right places. All UI elements you need to have assess to must be given instance names. Then you create a class for this MovieClip:
package
{
public class Layout extends MovieClip
{
// Left, Right, Up and Down are instance names of the objects
// in your designed MovieClip. Their accessors must be public.
// Also you should understand what classes they should be:
// SimpleButton for button object, TextField or TLFTextField
// for texts, MovieClip or Sprite for containers.
public var Left :SimpleButton;
public var Right:SimpleButton;
public var Up :SimpleButton;
public var Down :SimpleButton;
// Then if you set everything right you can access then
// in the class constructor with no need to create them
// or set them up as they are already in their places by design.
function Layout()
{
super();
Left.addEventListener(...);
}
}
}
I can't seem to find the source of the 1026 error:
import flash.events.KeyboardEvent;
import flash.events.Event;
import flash.ui.Keyboard;
import flash.display.MovieClip;
import flash.display.DisplayObject;
import flash.events.*;
import flash.display.Sprite;
import fl.controls.ProgressBar;
stop();
var NueMCSpeed:Number = 10;
var _movingUp:Boolean = false;
var _movingDown:Boolean = false;
var _movingLeft:Boolean = false;
var _movingRight:Boolean = false;
var _focused:Boolean = false;
var _attacking:Boolean = false;
var ShootAllow:Boolean = true;
var timer:Number = 2;
var shotN:Number = 0;
var SHOTINDEX:Number = 0;
NueMC.gotoAndStop("NueG");
var _root:Object;
var speed:int = 10;
Mainp();
function Mainp()
{
//var NueMC:MovieClip;
// add listeners
stage.addEventListener(Event.ENTER_FRAME, enterFrameHandler);
stage.addEventListener(KeyboardEvent.KEY_DOWN, myOnPress);
stage.addEventListener(KeyboardEvent.KEY_UP, myOnRelease);
}
function createPlayer():void
{
var NueMC:MovieClip;
NueMC.x = stage.stageWidth / 2;
NueMC.y = stage.stageHeight / 2;
stage.addChild(NueMC);
}
function myOnPress(event:KeyboardEvent):void
{
switch ( event.keyCode )
{
case Keyboard.UP :
_movingUp = true;
NueMC.gotoAndStop("NueG");
break;
case Keyboard.DOWN :
_movingDown = true;
NueMC.gotoAndStop("NueG");
break;
case Keyboard.LEFT :
_movingLeft = true;
NueMC.gotoAndStop("NueL");
break;
case Keyboard.RIGHT :
_movingRight = true;
NueMC.gotoAndStop("NueR");
break;
case Keyboard.SHIFT :
_focused = true;
break;
case Keyboard.Z :
_attacking = true;
//timer++
//if(timer == 3){
//shoot();
//timer = 0
//}
break;
}
}
function myOnRelease(event:KeyboardEvent):void
{
switch ( event.keyCode )
{
case Keyboard.UP :
_movingUp = false;
NueMC.gotoAndStop("NueG");
break;
case Keyboard.DOWN :
_movingDown = false;
NueMC.gotoAndStop("NueG");
break;
case Keyboard.LEFT :
_movingLeft = false;
NueMC.gotoAndStop("NueG");
break;
case Keyboard.RIGHT :
_movingRight = false;
NueMC.gotoAndStop("NueG");
break;
case Keyboard.SHIFT :
_focused = false;
break;
case Keyboard.Z :
_attacking = false;
break;
}
}
function enterFrameHandler(event:Event):void
{
if (_focused == true)
{
NueMCSpeed = 5;
ShootAllow = true
}
if (_focused == false)
{
NueMCSpeed = 10;
}
if ( _movingLeft && !_movingRight )
{
NueMC.x -= NueMCSpeed;
}
if ( _movingRight && !_movingLeft )
{
NueMC.x += NueMCSpeed;
}
if ( _movingUp && !_movingDown )
{
NueMC.y -= NueMCSpeed;
}
if ( _movingDown && !_movingUp )
{
NueMC.y += NueMCSpeed;
}
if(NueMC.y < 165)
{
NueMC.y = 165
}
if(NueMC.y > 885)
{
NueMC.y = 885
}
if(NueMC.x > 520)
{
NueMC.x = 520
}
if(NueMC.x < 10)
{
NueMC.x = 10
}
// Move diagonally
if ( _movingLeft && _movingUp && !_movingRight && !_movingDown )
{
}
if ( _movingRight && _movingUp && !_movingLeft && !_movingDown )
{
}
if ( _movingLeft && _movingDown && !_movingRight && !_movingUp )
{
}
if ( _movingRight && _movingDown && !_movingLeft && !_movingUp )
{
}
}
var pIsDead:Boolean = false;
var LSP:Number = .1;
var NP:Number = .0001;
var vx:Number = NueMC.x;
var vy:Number = NueMC.y;
var BHPN:Number = BHP.scaleX
if(ShootAllow == true && _attacking == true)
{
stageRef.addChild(new Bullet(stageRef, x + vx, y + vy));
ShootAllow = false;
}
if (NueMC.NHB.hitTestObject(stage.DBS.DBHB) && NueLB.scaleX > .1)
{
NueLB.scaleX -= LSP;
Score -=10000;
NueMC.gotoAndStop("NueDie");
pIsDead = true;
}
And then in an .as file I have:
package
{
import flash.display.MovieClip;
import fl.controls.ProgressBar;
import flash.display.Stage;
import flash.events.Event;
public class Bullet2 extends flash.display.MovieClip
{
private var stageRef2:Stage;
private var bulletSpeed:Number = 20;
public function Bullet2(stageRef:Stage, xd:Number, yd:Number):void
{
this.stageRef = stageRef2;
this.x = xd;
this.y = yd;
addEventListener(Event.ENTER_FRAME, loop, false, 0, true);
}
private function loop(e:Event):void
{
y -= bulletSpeed;
if (y < 125)
{
removeSelf();
}
}
private function removeSelf():void
{
removeEventListener(Event.ENTER_FRAME, loop);
if (stageRef.contains(this))
{
stageRef.removeChild(this);
}
}
}
}
I need to finish this program soon so help is greatly appreciated. PS code is long as I have no idea where the error is since flash doesn't want to give me the line.
The error is in this line: function Mainp() The problem is that it is located on the timeline, you cannot place constructors on the timeline. You should find the main *.as file and place that Mainp() in there, inside the class Mainp definition.
I'm having troubles with getting my textfield to fade from alpha 0 to alpha 1 with Tweener.
Everything else works fine, so I suspect it has something to do with applying my textformats on the textfield?
This is my code
private function swapText(e:Event):void {
applyTextFormats();
addChild(_textContainer);
var textfromx:int = _xmlData.image[_currentActiveSlide].textfromx;
var textfromy:int = _xmlData.image[_currentActiveSlide].textfromy;
var textendx:int = _xmlData.image[_currentActiveSlide].textendx;
var textendy:int = _xmlData.image[_currentActiveSlide].textendy;
_textTimer.stop();
var texteffectDuration:uint = _xmlData.image[_currentActiveSlide].texteffectduration;
var texteffectType:int = _xmlData.image[_currentActiveSlide].texteffecttype;
_effectDelay = _xmlData.image[_currentActiveSlide].effectdelay;
if(texteffectType == 1) {
_textContainer.x = textfromx;
_textContainer.y = textfromy;
Tweener.addTween(_textContainer, { x:textendx, y:textendy, time:texteffectDuration, onComplete:function() { _slideTimer.start(); } } );
}
else {
_textContainer.alpha = 0;
_textContainer.x = textendx;
_textContainer.y = textendy;
Tweener.addTween(_textContainer, { alpha:1, time:texteffectDuration, onComplete:function() { _slideTimer.start(); } } );
}
}
private function applyTextFormats():void {
_textContainer.text = _xmlData.image[_currentActiveSlide].imgtext;
_textContainer.width = _imgWidth;
_textContainer.height = 40;
_formatsText.size = _xmlData.image[_currentActiveSlide].fontsize;
_formatsText.align = TextFormatAlign.CENTER;
_formatsText.color = _xmlData.image[_currentActiveSlide].fontcolor;
_formatsText.font = _xmlData.#fontface;
if (_xmlData.image[_currentActiveSlide].fontbold == 1) {
_formatsText.bold = true;
}
else { _formatsText.bold = false; }
_textContainer.setTextFormat(_formatsText);
}
make sure you are embeding the fonts properly and to set textField.embedFont=true.