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();
}
Related
I have the following code for a game that manages display patterns for items by randomly deciding on one, creating the items based on the pattern chosen and then animating them.
The problem is that cleaning code and managing changes can be cumbersome due to the sheer size, I have been studying design patterns lately and I was wondering which would be the best one to apply here, so far I have considered strategy and command as possible options
"The strategy pattern is used to create an interchangeable family of algorithms from which the required process is chosen at run-time." Seems like something I could use to apply the positioning of the items depending on the pattern selected.
And by looking at previous questions here when asked about reducing the amount of if/elses the command pattern came up quite a bit.
" The command pattern is used to express a request, including the call to be made and all of its required parameters, in a command object. The command may then be executed immediately or held for later use."
Still, I don't know if I may be finding relevance where there is not, so I thought I'd ask if such patterns can be applied to the following scenarios.
Below is the relevant code, I'm specially interested in learning about this because almost the same code is repeated for enemies.
/**
* Set items pattern.
*
*/
private function setItemsPattern():void
{
// Change until enough flight distance has been accumulated.
if (patternChange > 0)
{
patternChange -= playerSpeed * elapsed;
}
else
{
// As the player moves, change item patterns.
if ( Math.random() < 0.7 )
{
// If < normal item chance (0.7), get a random pattern.
pattern = Math.ceil(Math.random() * 4);
}
else
{
// If random number is > normal item chance (0.3), create special item.
pattern = Math.ceil(Math.random() * 2) + 9;
}
if (pattern == GameConstants.ITEM_PATTERN_VERTICAL)
{
// Vertical
patternStep = 15;
patternChange = Math.random() * 500 + 500;
}
else if (pattern == GameConstants.ITEM_PATTERN_HORIZONTAL)
{
// Horizontal
patternOnce = true;
patternStep = 40;
patternChange = patternGap * Math.random() * 3 + 5;
}
else if (pattern == GameConstants.ITEM_PATTERN_ZIGZAG)
{
// ZigZag
patternStep = Math.round(Math.random() * 2 + 2) * 10;
if ( Math.random() > 0.5 )
{
patternDirection *= -1;
}
patternChange = Math.random() * 800 + 800;
}
else if (pattern == GameConstants.ITEM_PATTERN_RANDOM)
{
// Random
patternStep = Math.round(Math.random() * 3 + 2) * 50;
patternChange = Math.random() * 400 + 400;
}
else
{
patternChange = 0;
}
}
}
/**
* Creates items - called by createPattern()
*
*/
private function createItems():void
{
var itemToTrack:Item;
switch (pattern)
{
case GameConstants.ITEM_PATTERN_HORIZONTAL:
// Horizontal.
if (Math.random() > 0.9)
{
// Asignes items not too close to border.
patternPosY = Math.floor(Math.random() * (gameArea.bottom - gameArea.top + 1)) + gameArea.top;
}
itemToTrack = itemFactory.getItem(GameConstants.ITEM_TYPE_1);
this.addChild(itemToTrack);
// Sets pos
itemToTrack.x = stage.stageWidth + itemToTrack.width ;
itemToTrack.y = patternPosY;
// Marks item for animation
itemsToAnimate.push(itemToTrack);
break;
case GameConstants.ITEM_PATTERN_VERTICAL:
// Vertical
if (patternOnce == true)
{
patternOnce = false;
patternPosY = Math.floor(Math.random() * (gameArea.bottom - gameArea.top + 1)) + gameArea.top;
patternLength = (Math.random() * 0.4 + 0.4) * stage.stageHeight;
}
patternPosYstart = patternPosY;
while (patternPosYstart + patternStep < patternPosY + patternLength && patternPosYstart + patternStep < stage.stageHeight * 0.8)
{
itemToTrack = itemFactory.getItem(GameConstants.ITEM_TYPE_1);
this.addChild(itemToTrack);
itemToTrack.x = stage.stageWidth + itemToTrack.width;
itemToTrack.y = patternPosYstart;
itemsToAnimate.push(itemToTrack)
patternPosYstart += patternStep;
}
break;
case GameConstants.ITEM_PATTERN_ZIGZAG:
// ZigZag
if (patternDirection == 1 && patternPosY > gameArea.bottom - 50)
{
patternDirection = -1;
}
else if ( patternDirection == -1 && patternPosY < gameArea.top )
{
patternDirection = 1;
}
if (patternPosY >= gameArea.top && patternPosY <= gameArea.bottom)
{
itemToTrack = itemFactory.getItem(GameConstants.ITEM_TYPE_1);
this.addChild(itemToTrack);
itemToTrack.x = stage.stageWidth + itemToTrack.width;
itemToTrack.y = patternPosY;
itemsToAnimate.push(itemToTrack)
patternPosY += patternStep * patternDirection;
}
else
{
patternPosY = gameArea.top;
}
break;
case GameConstants.ITEM_PATTERN_RANDOM:
// Random, creates N amount of items on screen.
if (Math.random() > 0.3)
{
patternPosY = Math.floor(Math.random() * (gameArea.bottom - gameArea.top + 1)) + gameArea.top;
while (patternPosY + patternStep < gameArea.bottom)
{
itemToTrack = itemFactory.getItem(GameConstants.ITEM_TYPE_1);
this.addChild(itemToTrack);
itemToTrack.x = stage.stageWidth + itemToTrack.width;
itemToTrack.y = patternPosY;
itemsToAnimate.push(itemToTrack)
patternPosY += Math.round(Math.random() * 100 + 100);
}
}
break;
case GameConstants.ITEM_PATTERN_SPEED:
// special item
patternPosY = Math.floor(Math.random() * (gameArea.bottom - gameArea.top + 1)) + gameArea.top;
itemToTrack = itemFactory.getItem(GameConstants.ITEM_TYPE_MANA);
this.addChild(itemToTrack);
itemToTrack.x = stage.stageWidth + itemToTrack.width;
itemToTrack.y = patternPosY;
itemsToAnimate.push(itemToTrack);
break;
case GameConstants.ITEM_PATTERN_STR:
// special item
patternPosY = Math.floor(Math.random() * (gameArea.bottom - gameArea.top + 1)) + gameArea.top;
itemToTrack = itemFactory.getItem(GameConstants.ITEM_TYPE_REFERENCIA);
this.addChild(itemToTrack);
itemToTrack.x = stage.stageWidth + itemToTrack.width;
itemToTrack.y = patternPosY;
itemsToAnimate.push(itemToTrack);
break;
}
}
/**
* Animates the vector itemsToAnimate.
*
*/
private function animateItems():void
{
var itemToTrack:Item;
for(var i:uint = 0;i<itemsToAnimate.length;i++)
{
itemToTrack = itemsToAnimate[i];
if (itemToTrack != null)
{
if (referencia > 0 && itemToTrack.itemType <= GameConstants.ITEM_TYPE_REFERENCIA)
{
itemToTrack.x -= (itemToTrack.x - brujaX) * 0.2;
itemToTrack.y -= (itemToTrack.y - brujaY) * 0.2;
}
else
{
itemToTrack.x -= playerSpeed * elapsed;
}
if (itemToTrack.x < -80 || gameState == GameConstants.GAME_STATE_OVER)
{
disposeItemTemporarily(i, itemToTrack);
}
else
{
brujaItem_xDist = itemToTrack.x - brujaX;
brujaItem_yDist = itemToTrack.y - brujaY;
brujaItem_sqDist = brujaItem_xDist * brujaItem_xDist + brujaItem_yDist * brujaItem_yDist;
if (brujaItem_sqDist < 5000)
{
if (itemToTrack.itemType == GameConstants.ITEM_TYPE_1)
{
scoreItems += itemToTrack.itemType;
hud.itemScore = scoreItems;
if (!Sounds.muted) Sounds.sndPag.play();
}
else if (itemToTrack.itemType == GameConstants.ITEM_TYPE_MANA)
{
scoreItems += 1;
mana = 5;
if (isHardwareRendering) particleMana.start(mana);
if (!Sounds.muted) Sounds.sndMana.play();
if (!Sounds.muted) Sounds.sndRisa.play();
}
else if (itemToTrack.itemType == GameConstants.ITEM_TYPE_REFERENCIA)
{
scoreItems += 1;
referencia = 20;
partRef = 0.5;
if (isHardwareRendering) particleRef.start(partRef);
playRandomRef();
}
if(referencia > 0){referencia--;}
disposeItemTemporarily(i, itemToTrack);
}
}
}
}
}
Your function setItemsPattern and createItems both contain a switch-case statement, so you could create a base class contains two functions hanlde the switch-case work.
For example, you get the base class like this
Class BaseBehavior
{
//if the variable shouldn't be accessed by other class, change public to protected
public var patternOnce:Boolean;
public var patternStep:int;
public var patternChange:int;
public var patternDirection:int;
public var itemToTrack:Object;
public var gameArea:Object;
//used in setItemsPattern function
public function initPatternData():void {};
//used in createItems function
public function createItems():void {};
public function dispose():void {};
}
And here is the vertical class
Class VerticalBehavior extends BaseBehavior
{
override public function initPatternData():void
{
patternStep = 15;
patternChange = Math.random() * 500 + 500;
}
override public function createItems():void
{
if (Math.random() > 0.9)
{
// Asignes items not too close to border.
patternPosY = Math.floor(Math.random() * (gameArea.bottom - gameArea.top + 1)) + gameArea.top;
}
itemToTrack = itemFactory.getItem(GameConstants.ITEM_TYPE_1);
// Sets pos
itemToTrack.x = stage.stageWidth + itemToTrack.width ;
itemToTrack.y = patternPosY;
}
}
Other sub classes are most same.
Now you need a factory class to create the sub class
Class BehaviorFactory
{
public static function create(type:int):BaseBehavior
{
switch(type)
{
case 1://vertical
return new VerticalBehavior();
case 2:
return ...
...
}
}
}
After these work, you can use them in your old logic code
private var behavior:BaseBehavior;
private function setItemsPattern():void
{
if (behavior && behavior.patternChange > 0)
{
behavior.patternChange -= playerSpeed * elapsed;
}
else
{
// As the player moves, change item patterns.
if ( Math.random() < 0.7 )
{
// If < normal item chance (0.7), get a random pattern.
pattern = Math.ceil(Math.random() * 4);
}
else
{
// If random number is > normal item chance (0.3), create special item.
pattern = Math.ceil(Math.random() * 2) + 9;
}
//here to create the sub class
//dispose old behavior
if (behavior)
{
behavior.dispose();
}
behavior = BehaviorFactory.create(pattern);
}
private function createItems():voidh
{
//you may check behavior is null here
var itemToTrack:Item = behavior.createItems();
this.addChild(itemToTrack);
// Marks item for animation
itemsToAnimate.push(itemToTrack);
}
At last, if you want add a new type, you just need to create a sub behavior class and add it to the factory class.But be careful if the variables in the behavior increase too many, you may need to use composition class.
I'm trying to make a character able to move within the "world" movieclip, but not go through the walls.
So here is the character class, pretty basic. The moving variable dictates whether the character will move or not.
The issue is, when I move the character left or right against the "world" the character will move upwards or downwards as well.
// Code to move character
package
{
import flash.display.*;
import flash.events.*;
import flash.ui.*;
public class Character extends MovieClip
{
public var Moving:Boolean = true;
public var maxSpeed = 10;
public var dx = 0;
public var dy = 0;
public var rot = 0;
public var rof = 30;
private var keysDown:Array = new Array ;
// Declare variables:
//var bullet:Bullet;
var reload:int = 10;
private var bullets:Array;
public function Character()
{
//bullets = bulletList;
// Initialize variables:
addEventListener(Event.ADDED_TO_STAGE,init);
}
function init(e:Event):void
{
stage.addEventListener(KeyboardEvent.KEY_DOWN,keyPressed);
stage.addEventListener(KeyboardEvent.KEY_UP,keyReleased);
this.addEventListener(Event.ENTER_FRAME,processInput);
this.addEventListener(Event.ENTER_FRAME,moveMe);
removeEventListener(Event.ADDED_TO_STAGE,init);
}
public function removeT():void
{
stage.removeEventListener(KeyboardEvent.KEY_DOWN,keyPressed);
stage.removeEventListener(KeyboardEvent.KEY_UP,keyReleased);
this.removeEventListener(Event.ENTER_FRAME,processInput);
this.removeEventListener(Event.ENTER_FRAME,moveMe);
}
private function keyPressed(e:KeyboardEvent):void
{
keysDown[e.keyCode] = true;
// Handle keys pressed:
}
private function keyReleased(e:KeyboardEvent):void
{
keysDown[e.keyCode] = false;
}
private function processInput(e:Event)
{
// Handle keys held:
dx = 0;
dy = 0;
if (keysDown[Keyboard.LEFT])
{
dx = - maxSpeed;
dy = 0;
rot = -180;
this.gotoAndStop(4);
}
if (keysDown[Keyboard.RIGHT])
{
dx = maxSpeed;
dy = 0;
rot = 0;
this.gotoAndStop(1);
}
if (keysDown[Keyboard.UP])
{
dx = 0;
dy = - maxSpeed;
rot = -90;
this.gotoAndStop(3);
}
if (keysDown[Keyboard.DOWN])
{
this.gotoAndStop(2);
dx = 0;
dy = maxSpeed;
rot = 90;
}
}
private function moveMe(e:Event)
{
if(Moving){
this.x += dx;
this.y += dy;
this.rotation = rot;
}
//stop if it tries to go off the screen
if (this.x < 0)
{
this.x = 0;
}
if (this.x > stage.stageWidth)
{
this.x = stage.stageWidth;
}
if (this.y < 0)
{
this.y = 0;
}
if (this.y > stage.stageHeight)
{
this.y = stage.stageHeight;
}
}
}
}
Here is the code for the collision checking of the object and the world. I use the functions checkFrom and checkFromX to check the points around the movieclip. So when one of those functions are checked, it iterates through all the points on that side of the movieclip character
picture of the movieclip character if anyone is confused. http://prntscr.com/5fqu69
function checkFrom(x1:int, x2:int, y:int )
{
if (x2<x1) {
trace("x2<x1");
return false;
}
for (var i=x1; i<=x2; i++)
{
if (world.hitTestPoint(i,y,true))
{
return true;
}
}
return false;
}
//made this to check for right and left
function checkFromX(y1:int, y2:int, x:int )
{//y1 at top
if (y2<y1) {
trace("y2<y1");
return false;
}
for (var a=y1; a<=y2; a++)
{
if (world.hitTestPoint(x,a,true))
{
return true;
}
}
return false;
}
function moveDude(e:Event):void
{
var obj:Object = e.target;
if (obj.hitTestObject(world.lv1))
{
cleanup();
gotoAndStop("donkeyKong");
}
else
{
obj.Moving = true;
while (checkFrom(obj.x - obj.width / 2 + obj.width / 8,obj.x + obj.width / 2 - obj.width / 8,obj.y + obj.height / 2 - obj.height / 9))
{//bot
obj.y--;
obj.Moving = false;
}
while (checkFrom(obj.x - obj.width / 2 + obj.width / 8,obj.x + obj.width / 2 - obj.width / 8,obj.y - obj.height / 2 + obj.height / 9))
{
obj.y++;
obj.Moving = false;
}
while (checkFromX(obj.y - obj.height / 2 + obj.height / 7,obj.y - obj.height / 7 + obj.height / 2,obj.x - obj.width / 2 + obj.width / 9))
{//left
obj.x++;
obj.Moving = false;
}
while (checkFromX(obj.y - obj.height / 2 + obj.height / 7,obj.y + obj.height / 2 - obj.height / 7,obj.x + obj.width / 2 - obj.width / 9))
{
obj.x--;
obj.Moving = false;
}
Im getting an weird error about constructions definitions that i have no idea what means.
Im studing this for a test.I think the problem is on the functions but im not sure.
Its a code from an game (pretty simple one) that you have to move your player from point b to point a without letting the falling asteroids touch you.
Thanks in advance.
import flash.display.MovieClip;
import flash.events.KeyboardEvent;
import flash.ui.Keyboard;
import flash.events.Event;
var up:Boolean;
var down:Boolean;
var left:Boolean;
var right:Boolean;
var vel:Number;
var velInimigo:Number;
var sentidoX:Number;
var sentidoY:Number;
var d:MovieClip;
var txt1:MovieClip;
var chegada:MovieClip;
var player:MovieClip;
var inimigos:Array;
var i:int;
var mc:MovieClip;
function MainTimeline()
{
addFrameScript(0, frame1);
return;
}
function OnKeyDown(event:KeyboardEvent) : void
{
switch(event.keyCode)
{
case Keyboard.W:
{
up = true;
break;
}
case Keyboard.S:
{
down = true;
break;
}
case Keyboard.A:
{
left = true;
break;
}
case Keyboard.D:
{
right = true;
break;
}
default:
{
break;
}
}
return;
}
function OnKeyUp(event:KeyboardEvent) : void
{
switch(event.keyCode)
{
case Keyboard.W:
{
up = false;
break;
}
case Keyboard.S:
{
down = false;
break;
}
case Keyboard.A:
{
left = false;
break;
}
case Keyboard.D:
{
right = false;
break;
}
default:
{
break;
}
}
return;
}
function OnFrame(event:Event) : void
{
var loc3: = null;
var loc4: = null;
if (up)
{
sentidoY = -1;
}
else if (down)
{
sentidoY = 1;
}
else
{
sentidoY = 0;
}
if (left)
{
sentidoX = -1;
}
else if (right)
{
sentidoX = 1;
}
else
{
sentidoX = 0;
}
if (sentidoX == 1 && sentidoY == 0)
{
player.rotation = 0 + 90;
}
else if (sentidoX == 1 && sentidoY == 1)
{
player.rotation = 45 + 90;
}
else if (sentidoX == 0 && sentidoY == 1)
{
player.rotation = 90 + 90;
}
else if (sentidoX == -1 && sentidoY == 1)
{
player.rotation = 135 + 90;
}
else if (sentidoX == -1 && sentidoY == 0)
{
player.rotation = 180 + 90;
}
else if (sentidoX == -1 && sentidoY == -1)
{
player.rotation = 225 + 90;
}
else if (sentidoX == 0 && sentidoY == -1)
{
player.rotation = 270 + 90;
}
else if (sentidoX == 1 && sentidoY == -1)
{
player.rotation = 315 + 90;
}
player.x = player.x + vel * sentidoX;
player.y = player.y + vel * sentidoY;
var loc2: = 0 ;
while (loc2 < inimigos.length)
{
loc3 = inimigos[loc2];
loc3.y = loc3.y + loc3.vel;
loc3.rotation = loc3.rotation + loc3.rotVel;
if (loc3.hitTestObject(player))
{
loc4 = new GameOverMC();
stage.addChild(loc4);
loc4.x = stage.stage.width / 2;
loc4.y = stage.stageHeight / 2;
stage.removeEventListener(Event.ENTERFRAME, OnFrame);
}
if (loc3.y > stage.stageHeight)
{
loc3.y = -loc3.height;
}
loc2++;
}
if (player.hitTestObject(chegada))
{
if (txt1 == null)
{
txt1 = new VitoriaMC();
stage.addChild(txt1);
txt1.x = stage.stage.width / 2;
txt1.y = stage.stageHeight / 2;
}
}
d.x = d.x + d.vel * d.sx;
d.y = d.y + d.vel * d.sy;
if (d.x >= stage.stageWidth - d.width / 2 || d.x <= d.width / 2)
{
d.sx = -d.sx;
}
if (d.y >= stage.stageHeight - d.height / 2 || d.y <= d.height / 2)
{
d.sy = -d.sy;
}
return;
}
function frame1()
{
vel = 5;
velInimigo = 2;
sentidoX = 0;
sentidoY = 0;
d = new DemoMC();
d.vel = 1;
d.sx = 1;
d.sy = 1;
d.x = stage.stageWidth / 2;
d.y = stage.stageHeight / 2;
txt1 = null;
chegada = new ChegadaMC();
player = new PlayerMC();
inimigos = new Array();
stage.addChild(d);
stage.addChild(chegada);
stage.addChild(player);
player.x = player.width / 2;
player.y = stage.stageHeight - player.height / 2;
chegada.x = stage.stageWidth - chegada.width;
chegada.y = 0;
i = 0;
while (i < 60)
{
mc = new AstroMC();
stage.addChild(mc);
inimigos.push(mc);
mc.x = 100 + Math.random() * (600 - mc.width);
mc.y = Math.random() * stage.stageHeight;
mc.rotVel = Math.random() * 10 - 5;
mc.vel = Math.random() * 3 + 1;
var loc1: = i;
var loc2: = i + 1;
loc1.i = loc2;
}
stage.addEventListener(KeyboardEvent.KEYDOWN, OnKeyDown);
stage.addEventListener(KeyboardEvent.KEYUP, OnKeyUp);
stage.addEventListener(Event.ENTERFRAME, OnFrame);
return;
}
It has been awhile since i have played with AS3 but i see a few odd things one being the
loc1.i = loc2;
near the bottom
what is "i" in relation to loc1? and this is in a while loop using i but never increments it so it seems like an infinite loop
again i could be wrong its been quite some time.
I'm trying to add the maths to control a panorama with the gyroscope and struggling. This is a mobile app built in AS3.
I've got the data coming through from the gyroscope (x and y), and I've got the current angle (pan and tilt). What I want to do is update the cameraController with the new angle based on the data from the gyro.
I've been attempting to convert the Javascript I found on https://github.com/fieldOfView/krpano_fovplugins/blob/master/gyro/source/gyro.source.js into Actionscript 3, and it kind of works - but not really.
EDIT
Thanks I tried those changes and I added camera roll back in because the euler maths needed it, it runs but there is something wrong with the Maths.
The panorama only seems to drift up and left, after a while of moving the phone the other way it drifts down, and then moves right.
Can you see anything important I'm missing from the Javascript?
import com.adobe.nativeExtensions.GyroscopeEvent;
import flash.events.Event;
import flash.geom.Orientation3D;
public class GyroscopeMaths
{
public function GyroscopeMaths()
{
super();
}
private var isTopAccessible:Boolean = false;
private var isDeviceAvailable:Boolean;
private var isEnabled:Boolean = false;
private var vElasticity:Number = 0;
private var isVRelative:Boolean = false;
private var isCamRoll:Boolean = false;
private var friction:Number = 0.5;
private var isTouching:Boolean = false;
private var validSample:Boolean = false;
private var firstSample:* = null;
private var hOffset:Number = 0;
private var vOffset:Number = 0;
private var hLookAt:Number = 0;
private var vLookAt:Number = 0;
private var camRoll:Number = 0;
private var vLookAtNow:Number = 0;
private var hLookAtNow:Number = 0;
private var hSpeed:Number = 0;
private var vSpeed:Number = 0;
private var vElasticSpeed:Number = 0;
private var camRollNow:Number;
private var pitch:Number;
private var yaw:Number;
private var altYaw:Number;
private var factor:Number;
private var degRad:Number = Math.PI / 180;
public function handleDeviceOrientation(x:Number, y:Number, z:Number):void {
// Process event.alpha, event.beta and event.gamma
var orientation:* = rotateEuler({
"yaw":y * degRad,
"pitch":x * degRad,
"roll": z * degRad
});
yaw = wrapAngle(orientation.yaw / degRad);
pitch = orientation.pitch / degRad;
altYaw = yaw, factor;
hLookAtNow = Pano.instance.pan;
vLookAtNow = Pano.instance.tilt;
hSpeed = hLookAtNow - hLookAt,
vSpeed = vLookAtNow - vLookAt;
// Ignore all sample until we get a sample that is different from the first sample
if (!validSample) {
if (firstSample == null) {
firstSample = orientation;
} else {
if (orientation.yaw != firstSample.yaw || orientation.pitch != firstSample.pitch || orientation.roll != firstSample.roll) {
firstSample = null;
validSample = true;
if (isVRelative) {
vOffset = -pitch;
}
}
}
return;
}
// Fix gimbal lock
if (Math.abs(pitch) > 70) {
altYaw = y;
var altYaw:Number = wrapAngle(altYaw);
if (Math.abs(altYaw - yaw) > 180) {
altYaw += (altYaw < yaw) ? 360 :-360;
}
var factor:Number = Math.min(1, (Math.abs(pitch) - 70) / 10);
yaw = yaw * (1 - factor) + altYaw * factor;
//camRoll *= (1 - factor);
}
// Track view change since last orientation event
// ie:user has manually panned, or krpano has altered lookat
hOffset += hSpeed;
vOffset += vSpeed;
// Clamp vOffset
if (Math.abs(pitch + vOffset) > 90) {
vOffset = (pitch + vOffset > 0) ? (90 - pitch) :(-90 - pitch)
}
hLookAt = wrapAngle(-yaw - 180 + hOffset);
vLookAt = Math.max(Math.min((pitch + vOffset), 90), -90);
// Dampen lookat
if (Math.abs(hLookAt - hLookAtNow) > 180) {
hLookAtNow += (hLookAt > hLookAtNow) ? 360 :-360;
}
hLookAt = (1 - friction) * hLookAt + friction * hLookAtNow;
vLookAt = (1 - friction) * vLookAt + friction * vLookAtNow;
if (Math.abs(camRoll - camRollNow) > 180) {
camRollNow += (camRoll > camRollNow) ? 360 :-360;
}
camRoll = (1 - friction) * camRoll + friction * camRollNow;
var wAh:Number = wrapAngle(hLookAt);
Pano.instance.panoGyroChange(wAh, vLookAt);
//krpano.view.camroll = wrapAngle(camRoll);
if (vOffset != 0 && vElasticity > 0) {
if (vSpeed == 0) {
if (vElasticity == 1) {
vOffset = 0;
vElasticSpeed = 0;
} else {
// vElasticSpeed = 1 - ((1 - vElasticSpeed) * krpano.control.touchfriction);
vOffset *= 1 - (Math.pow(vElasticity, 2) * vElasticSpeed); // use Math.pow to be able to use saner values
if (Math.abs(vOffset) < 0.1) {
vOffset = 0;
vElasticSpeed = 0;
}
}
} else {
vElasticSpeed = 0;
}
}
}
private function rotateEuler(euler:Object):Object {
// This function is based on http://www.euclideanspace.com/maths/geometry/rotations/conversions/eulerToMatrix/index.htm
// and http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToEuler/index.htm
trace(euler);
var heading:Number;
var bank:Number;
var attitude:Number;
var ch:Number = Math.cos(euler.yaw);
var sh:Number = Math.sin(euler.yaw);
var ca:Number = Math.cos(euler.pitch);
var sa:Number = Math.sin(euler.pitch);
var cb:Number = Math.cos(euler.roll);
var sb:Number = Math.sin(euler.roll);
var matrix:Array = [
sh * sb - ch * sa * cb, -ch * ca, ch * sa * sb + sh * cb,
ca * cb, -sa, -ca * sb,
sh * sa * cb + ch * sb, sh * ca, -sh * sa * sb + ch * cb
]; // Note:Includes 90 degree rotation around z axis
/* [m00 m01 m02] 0 1 2
* [m10 m11 m12] 3 4 5
* [m20 m21 m22] 6 7 8 */
if (matrix[3] > 0.9999) {
// Deal with singularity at north pole
heading = Math.atan2(matrix[2], matrix[8]);
attitude = Math.PI / 2;
bank = 0;
} else if (matrix[3] < -0.9999) {
// Deal with singularity at south pole
heading = Math.atan2(matrix[2], matrix[8]);
attitude = -Math.PI / 2;
bank = 0;
} else {
heading = Math.atan2(-matrix[6], matrix[0]);
bank = Math.atan2(-matrix[5], matrix[4]);
attitude = Math.asin(matrix[3]);
}
return {
yaw:heading,
pitch:attitude,
roll:bank
};
}
private function wrapAngle(value:Number):Number {
value = value % 360;
return (value <= 180) ? value :value - 360;
} // wrap a value between -180 and 180
//function stringToBoolean(value:Number):String
//{ return (String("yesontrue1").indexOf( String(value:Number) ) >= 0) };
}
Without the rest of your program, I won't be able to compile this, but I've corrected what syntactical errors I could find. That said, if you can program in either JS or As3, you should be able to follow the logic and write your own class (they're both EMCAScript). Continue pursuing that until you've arrived at a more solid problem than "it doesn't work" (which is generally a question no one wants to answer).
private var isTopAccessible:Boolean = false;
private var isDeviceAvailable:Boolean;
private var isEnabled:Boolean = false;
private var vElasticity:Number = 0;
private var isVRelative:Boolean = false;
private var isCamRoll:Boolean = false;
private var friction:Number = 0.5;
private var isTouching:Boolean = false;
private var validSample:Boolean = false;
private var firstSample:* = null;
private var hOffset:Number = 0;
private var vOffset:Number = 0;
private var hLookAt:Number = 0;
private var vLookAt:Number = 0;
private var camRoll:Number = 0;
private var vLookAtNow:Number = 0;
private var hLookAtNow:Number = 0;
private var hSpeed:Number = 0;
private var vSpeed:Number = 0;
private var vElasticSpeed:Number = 0;
private var camRollNow:Number;
private var pitch:Number;
private var yaw:Number;
private var altYaw:Number;
private var factor:Number;
private var degRad:Number = Math.PI / 180;
public function handleDeviceOrientation(x:Number, y:Number):void {
// Process event.alpha, event.beta and event.gamma
var orientation:* = rotateEuler({
"yaw":y * degRad,
"pitch":x * degRad,
"roll":0
});
yaw = wrapAngle(orientation.yaw / degRad);
pitch = orientation.pitch / degRad;
altYaw = yaw, factor;
hLookAtNow = Pano.instance.pan;
vLookAtNow = Pano.instance.tilt;
hSpeed = hLookAtNow - hLookAt,
vSpeed = vLookAtNow - vLookAt;
// Ignore all sample until we get a sample that is different from the first sample
if (!validSample) {
if (firstSample == null) {
firstSample = orientation;
} else {
if (orientation.yaw != firstSample.yaw || orientation.pitch != firstSample.pitch || orientation.roll != firstSample.roll) {
firstSample = null;
validSample = true;
if (isVRelative) {
vOffset = -pitch;
}
}
}
return;
}
// Fix gimbal lock
if (Math.abs(pitch) > 70) {
altYaw = y;
/*switch(deviceOrientation) {
case 0:
if ( pitch>0 )
altYaw += 180;
break;
case 90:
altYaw += 90;
break;
case -90:
altYaw += -90;
break;
case 180:
if ( pitch<0 )
altYaw += 180;
break;
}*/
var altYaw:Number = wrapAngle(altYaw);
if (Math.abs(altYaw - yaw) > 180) {
altYaw += (altYaw < yaw) ? 360 :-360;
}
var factor:Number = Math.min(1, (Math.abs(pitch) - 70) / 10);
yaw = yaw * (1 - factor) + altYaw * factor;
//camRoll *= (1 - factor);
}
// Track view change since last orientation event
// ie:user has manually panned, or krpano has altered lookat
hOffset += hSpeed;
vOffset += vSpeed;
// Clamp vOffset
if (Math.abs(pitch + vOffset) > 90) {
vOffset = (pitch + vOffset > 0) ? (90 - pitch) :(-90 - pitch)
}
hLookAt = wrapAngle(-yaw - 180 + hOffset);
vLookAt = Math.max(Math.min((pitch + vOffset), 90), -90);
// Dampen lookat
if (Math.abs(hLookAt - hLookAtNow) > 180) {
hLookAtNow += (hLookAt > hLookAtNow) ? 360 :-360;
}
hLookAt = (1 - friction) * hLookAt + friction * hLookAtNow;
vLookAt = (1 - friction) * vLookAt + friction * vLookAtNow;
if (Math.abs(camRoll - camRollNow) > 180) {
camRollNow += (camRoll > camRollNow) ? 360 :-360;
}
camRoll = (1 - friction) * camRoll + friction * camRollNow;
var wAh:Number = wrapAngle(hLookAt);
Pano.instance.panoGyroChange(wAh, vLookAt);
//krpano.view.camroll = wrapAngle(camRoll);
if (vOffset != 0 && vElasticity > 0) {
if (vSpeed == 0) {
if (vElasticity == 1) {
vOffset = 0;
vElasticSpeed = 0;
} else {
// vElasticSpeed = 1 - ((1 - vElasticSpeed) * krpano.control.touchfriction);
vOffset *= 1 - (Math.pow(vElasticity, 2) * vElasticSpeed); // use Math.pow to be able to use saner values
if (Math.abs(vOffset) < 0.1) {
vOffset = 0;
vElasticSpeed = 0;
}
}
} else {
vElasticSpeed = 0;
}
}
}
private function rotateEuler(euler:Object):Object {
// This function is based on http://www.euclideanspace.com/maths/geometry/rotations/conversions/eulerToMatrix/index.htm
// and http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToEuler/index.htm
trace(euler);
var heading:Number;
var bank:Number;
var attitude:Number;
var ch:Number = Math.cos(euler.yaw);
var sh:Number = Math.sin(euler.yaw);
var ca:Number = Math.cos(euler.pitch);
var sa:Number = Math.sin(euler.pitch);
var cb:Number = Math.cos(euler.roll);
var sb:Number = Math.sin(euler.roll);
var matrix:Array = [
sh * sb - ch * sa * cb, -ch * ca, ch * sa * sb + sh * cb,
ca * cb, -sa, -ca * sb,
sh * sa * cb + ch * sb, sh * ca, -sh * sa * sb + ch * cb
]; // Note:Includes 90 degree rotation around z axis
/* [m00 m01 m02] 0 1 2
* [m10 m11 m12] 3 4 5
* [m20 m21 m22] 6 7 8 */
if (matrix[3] > 0.9999) {
// Deal with singularity at north pole
heading = Math.atan2(matrix[2], matrix[8]);
attitude = Math.PI / 2;
bank = 0;
} else if (matrix[3] < -0.9999) {
// Deal with singularity at south pole
heading = Math.atan2(matrix[2], matrix[8]);
attitude = -Math.PI / 2;
bank = 0;
} else {
heading = Math.atan2(-matrix[6], matrix[0]);
bank = Math.atan2(-matrix[5], matrix[4]);
attitude = Math.asin(matrix[3]);
}
return {
yaw:heading,
pitch:attitude,
roll:bank
};
}
private function wrapAngle(value:Number):Number {
value = value % 360;
return (value <= 180) ? value :value - 360;
} // wrap a value between -180 and 180
//function stringToBoolean(value:Number):String
//{ return (String("yesontrue1").indexOf( String(value:Number) ) >= 0) };
I am trying to make a simple card matching game via flash + actionscript, and am having major trouble with assigning event listeners and name. I have got all the card generation statements in place, and they all draw onto my stage, but even though I assigning their instance name with newCard.name, the name I get when tracing the click is always "root1" on every single button, and I have no idea why.
package {
import flash.display.MovieClip;
import flash.events.MouseEvent;
public dynamic class cardGameMain extends MovieClip {
public function cardGameMain() {
addCards();
}
public function addCards() {
var lastCard:int;
for (var i = 1; i < 17; i++) {
var newCard:MovieClip;
newCard = new cardBackSymbol();
newCard.name = "card" + i;
addChild(newCard);
newCard.addEventListener(MouseEvent.MOUSE_UP, decideCard);
if (i == 1 || i == 5 || i == 9 || i == 13) {
newCard.x = 20;
if (i == 1) {
newCard.y = 20;
}
else if (i == 5) {
newCard.y = 240;
}
else if (i == 9) {
newCard.y = 460;
}
else if (i == 13) {
newCard.y = 680;
}
lastCard = 20;
} else if (i > 1 && i < 5) {
newCard.x = lastCard + 145;
newCard.y = 20;
lastCard = lastCard + 145;
} else if (i > 5 && i < 9) {
newCard.x = lastCard + 145;
newCard.y = 240;
lastCard = lastCard + 145;
} else if (i > 9 && i < 13) {
newCard.x = lastCard + 145;
newCard.y = 460;
lastCard = lastCard + 145;
} else {
newCard.x = lastCard + 145;
newCard.y = 680;
lastCard = lastCard + 145;
}
trace(newCard.name + " position is " + newCard.x + ", " + newCard.y);
}
}
public function decideCard(e:MouseEvent):void {
trace(this.name)
}
}
}
Any help on the matter is MUCH appretiated!
You're using the this keyword which is referring to the containing class, not the object clicked.
Try this instead:
public function decideCard(e:MouseEvent):void {
trace(DisplayObject(e.currentTarget).name)
}