Change a public var at runtime in as3? (flixel) - actionscript-3

I'm trying to create a guessing game that has the user clicking on different colored boxes to see which one is correct. I have a public var that dictates which color(later image) to use. The code is this in my update:
if (FlxG.mouse.justPressed())
{
block2.distributionp = Math.random() * 2;
block2.colorArray = block2.distributionp;
block2.colorUnit = block2.colorArray;
}
(colorUnit and colorArray both equal distributionp, which is a ranom of 2 in the class file)
When I run this code, the change does occur, but it only seems to switch out once. The other times it's ignored. How can I get this to continuously switch out a random number that I can use later?
Thanks in advance!

Math.random() * 2 Returns a Number ranging from 0.000000000000 to 2.00000000, this includes numbers like 0.123456789 and 1.99999999 (Not sure exactly what decimal place it goes to but just saying it doesn't only return integers 0, 1 and 2). I'm not sure but I think you're problem lies in the range, so if you want a better range use this code.
MIN_VALUE * Math.random() + (MAX_VALUE - MIN_VALUE);
If you would like to only get integers you can use either Math.ceil() or Math.floor() like so :
Math.ceil(MIN_VALUE * Math.random() + (MAX_VALUE - MIN_VALUE));
I'm sorry if this does not help you but let me know if it doesn't and I will continue to try and help.

The value I'm getting is whole integers between 0 and 2. What I'm trying to do, is change the vaue for each time I click. I'm not sure what occurs. Perhaps I shouldn't have asked now. I'll ask later when I have more info. Sorry.

Related

Razor: Display procentage

I thought there would be an easy solution but I didnt succeed in finding anything that worked!
var squatPro = sumTotalSquatWeight/sumTotalVolume;
It's basically just this line, I don't know how to make it to decimal, since the result now is just 0 when the numbers are 9120/14895 = 0,61.
Adding * 100 at the end of the code gave 0 as well so that wasn't a solution!
(I'm not using MVC)
You may need to cast the numerator to a decimal:
var squatPro = (decimal)sumTotalSquatWeight / sumTotalVolume;
And if you want to round to 2 decimal places you can use something like this:
#squatPro.ToString("0.##")
Or if you need it as a percentage you can use this:
#(string.Format("{0:P}", squatPro))

Inverted Smoothstep?

I am currently trying to simulate ballistics on an object, that is otherwise not affected by physics. To be precise, I have a rocket-like projectile, that is following an parabolic arc from origin to target with a Lerp. To make it more realistic, I want it not to move at constant speed, but to slow down towards the climax and speed up on its way back down.
I have used the Mathf.Smoothstep function to do the exact opposite of what i need on other objects, i.e. easing in and out of the motion.
So my question is: How do I get an inverted Smoothstep?
I found out that what i would need is actually the inverted formula to smoothstep [ x * x*(3 - 2*x) ], but being not exactly a math genius, I have no idea how to do that. All I got from online calculators was some pretty massive new function, which I'm afraid would not be very efficient.
So maybe there is a function that comes close to an inverted smoothstep, but isn't as complex to compute.
Any help on this would be much appreciated
Thanks in advance,
Tux
Correct formula is available here:
https://www.shadertoy.com/view/MsSBRh
Solution by Inigo Quilez and TinyTexel
Flt SmoothCubeInv(Flt y)
{
if(y<=0)return 0;
if(y>=1)return 1;
return 0.5f-Sin(asinf(1-2*y)/3);
}
I had a similar problem. For me, mirroring the curve in y = x worked:
So an implementation example would be:
float Smooth(float x) {
return x + (x - (x * x * (3.0f - 2.0f * x)));
}
This function has no clamping, so that may have to be added if x can go outside the 0 to 1 interval.
Wolfram Alpha example
If you're moving transforms, it is often a good idea to user iTween or similar animation libraries instead of controlling animation yourself. They have a an easy API and you can set up easing mode too.
But if you need this as a math function, you can use something like this:
y = 0.5 + (x > 0.5 ? 1 : -1) * Mathf.Pow(Mathf.Abs(2x - 1),p)/2
Where p is the measure of steepness that you want. Here's how it looks:
You seem to want a regular parabola. See the graph of this function:
http://www.wolframalpha.com/input/?i=-%28x%2A2-1%29%5E2%2B1
Which is the graph that seems to do what you want: -(x*2-1)^2+1
It goes from y=0 to y=1 and then back again between x=0 and x=1, staying a bit at the top around x=0.5 . It's what you want, if I understood it correctly.
Other ways to write this function, according to wolfram alpha, would be -(4*(x-1)*x) and (4-4*x)*x
Hope it helps.

Actionscript 3- Random movement on stage? Also, Boundaries?

I'm trying to code something where there are creatures running back and forth, up and down across the stage, and I the player, have to try to go up to them, and pick them up. There are also boundaries on stage-
The map constraints- a big rectangle box is easy enough to accomplish. I've done this.
The boundaries within the map, which are also rectangles, but instead of bouncing the player back INSIDE the rectangle, I'm trying to do the opposite- keep the player out of it.
My code for it looks like this as of now:
//Conditions that check if player/monsters are hittesting the boxes (rocks
//and stuff), then if correct, bounce them away. Following code excludes
//the monsters for simplicity.
if((mcPlayer.x - aBounceBox[b].x) < 0 && mcPlayer.y <= (aBounceBox[b].y + aBounceBox[b].height/2) && mcPlayer.y >= (aBounceBox[b].y - aBounceBox[b].height/2))
{
mcPlayer.x = aBounceBox[b].x - aBounceBox[b].width/2 - mcPlayer.width/2;
}
//Duplicate above code for right side of box here
if((mcPlayer.y - (aBounceBox[b].y + aBounceBox[b].height/2)) < 0 && (mcPlayer.x + mcPlayer.width/2) > (aBounceBox[b].x - aBounceBox[b].width/2) && (mcPlayer.x - mcPlayer.width/2) < (aBounceBox[b].x + aBounceBox[b].width/2))
{
mcPlayer.y = aBounceBox[b].y + aBounceBox[b].height/2;
}
//Duplicate above code for Upper boundary of box here
The above doesn't work very well because the code to bounce for the left and right sides of the box conflicts with the upper and lower parts of the box I'm hit-testing for. Any ideas how to do that smoothly?
Also, another problem I am having is the pathing for the monsters in the game. I'm trying to get them to do the following:
Move around "organically", or a little randomly- move a little, stop. If they encounter a boundary, they'd stop and move, elsewhere. Not concerned where to, as long as they stop moving into rocks and trees, things like that.
Not overlap as much as possible as the move around on stage.
To push each other apart if they are overlapping, although I'd like to allow them to overlap very slightly.
I'm building that code slowly, but I thought I'd just ask if anyone has any ideas on how to do that.
To answer your first question, you may try to implement a new class/object which indicates the xy-offset between two display objects. In order to illustrate the idea more clearly, you can have a function similar to this:
public function getOffset(source:DisplayObject, target:DisplayObject):Object {
var dx:Number = target.x - source.x;
var dy:Number = target.y - source.y;
return { x:dx, y:dy };
}
Check if the hero character is colliding with another object first by hitTestObject(displayObj) of DisplayObject class. Proceed if the result is true.
Suppose you pass in your hero character as the source object, and another obstacle as the target object,
var offset:Object = getOffset(my_hero.mc, some_obstacle.mc);
After getting the resulting offset values, compare the magnitude (absolute value) of offset.x and offset.y. The outcome can be summarized as follows:
Let absDx be Math.abs(offset.x), absDy be Math.abs(offset.y),
absDx < absDy
offset.y < 0, target is above source
offset.y > 0, target is below source
absDx > absDy
offset.x < 0, target is to the left of source
offset.x > 0, target is to the right of source
absDx == absDy
refer to one of the above cases, doesn't really matter
Then you can update the position of your hero character according to different situations.
For your second question concerning implementing a very simple AI algorithm for your creatures, you can make use of the strategy above for your creatures to verify if they collide with any other stuff or not. If they do collide, assign them other directions of movement, or even simpler, just flip the signs(+/-) of their velocities and they will travel in opposite directions.
It is easier to implement simple algorithms first. Once it is working, you can apply whatever enhancements you like afterwards. For example, change directions when reaching junctions or per 3 seconds etc.

Removing commas from multidimensional arrays

I'm having a bit of trouble removing commas from an array when I go to write it to a cell in google spreadsheets. array.join(''); doesn't seem to do the trick. I would appreciate any help. Also, anchor[i][j].join('') returns an error.
Here is a bit of code:
anchor[i][j].join('') returns an error
anchor[i].join('') doesn't seem to have an effect.
for (var i=0; i(less than) rangeKW.length-2;i++){
anchor[i] = [];
for (var j=0; j<rangeURL.length;j++){
anchor[i][j] = ahref + rangeKW[i] + ahref1 + rangeURL[j] + "</a>|";
}
}
cell.setValue("{" + anchor);
}
Suppose you have
var x = [[1,2,3],[4,5,6]]
Then either of these lines will give you "123456":
Array.prototype.concat.apply([], x).join('')
x.map(function(a){ return a.join(''); }).join('');
The first one constructs the array [1,2,3,4,5,6] and then joins it. The second one joins each inner array first, constructing ["123", "456"] and then joins that. I think the first one is likely to be a tiny bit more efficient, although we are talking peanuts here, but the second one gives you a bit more control if you want to put something different between rows and columns.
In both cases, this doesn't change the original value in x. You can assign the new value to x if that's what you want.
array.join() works with "normal" arrays, by normal I mean 1 dimension and applies to the array itself, not on an single element (error on [i][j]), beside that I don't really understand what you want to do and how your code is related to your question ...
concerning anchor[i].join('');// doesn't seem to have an effect. I don't know how many elements are in there and how they look like but the syntax is correct. You can also use toString() if you want to make it a CSV string.
EDIT : (thanks for the information in comments.)
I think the easiest way (or at least the most clear) would be to create a couple of new variables that you could log separately to see exactly what happens.
for example
var anchorString = anchor[i].join(); // or toString() they both return strings from 1D arrays
Logger.log(anchorString)
if every index i of anchor have to be in the same cell then write it like this in the i-loop :
var anchorString += anchor[i].join();
Logger.log(anchorString)

AS3 additive tone synthesis. playing multiple generated sounds

Inspired by Andre michelle, I`m building a tone matrix in AS3.
I managed to create the matrix and generate the different sounds. They don´t sound that good, but I´m getting there
One big problem I have is when more than one dot is set to play, it sounds just horrible. I googled a lot and found the additive synthesis method but don´t have a clue how to apply it to as3.
anybody out there knows how to play multiple sounds together? any hint?
my demo is at www.inklink.co.at/tonematrix
Oh common the sound was horrible...
Checked wiki? It is not that hard to understand... Even if you don't know that much of mathematics... Which you should - PROGRAMMING music is not easy.
So:
Let's first define something:
var harmonics:Array = new Array();
harmonics is the array in which we will store individual harmonics. Each child will be another array, containing ["amplitude"] (technically the volume), ["frequency"] and ["wavelength"] (period). We also need a function that can give us the phase of the wave given the amplitude, wavelength and offset (from the beginning of the wave). For square wave something like:
function getSquarePhase(amp:Number, wl:Number, off:Number):Number {
while (off > wl){off -= wl;}
return (off > wl / 2 ? -amp : amp); // Return amp in first half, -amp in 2.
}
You might add other types, or even custom vector waves if you want.
Now for the harder part.
var samplingFrequency; // set this to your SF
function getAddSyn(harmonics:Array, time:Number):Number {
if (harmonics.length == 1){ // We do not need to perform AS here
return getSquarePhase(harmonics[0]["amplitude"], harmonics[0]["wavelength"], time);
} else {
var hs:Number = 0;
hs += 0.5 * (harmonics[0]["amplitude"] * Math.cos(getSquarePhase(harmonics[0]["amplitude"], harmonics[0]["wavelength"], time)));
// ^ You can try to remove the line above if it does not sound right.
for (var i:int = 1; i < harmonics.length; i++){
hs += (harmonics[0]["amplitude"] * Math.cos(getSquarePhase(harmonics[0]["amplitude"], harmonics[0]["wavelength"], time)) * Math.cos((Math.PI * 2 * harmonics[0]["frequency"] / samplingFrequency) * time);
hs -= Math.sin(getSquarePhase(harmonics[0]["amplitude"], harmonics[0]["wavelength"], time)) * Math.sin((Math.PI * 2 * harmonics[0]["frequency"] / samplingFrequency) * time);
}
return hs;
}
}
This is all just converted (weakly :D) from the Wikipedia, I may have done a mistake somewhere in there... But I think you should get the idea... And if not, try to convert the AS from Wikipedia yourself, as I said, it is not so hard.
I also somehow ignored the Nyquist frequency...
I have tried your demo and thought it sounded pretty good actually. What do you mean it doesn't sound that good? What's missing? My main area of interest is music and I haven't found anything wrong , only it's a little frustrating , because after creating a sequence, I feel the need to add new sounds! Had I been able to record what I was playing with, I would have sent it to you.
Going into additive synthesis doesn't look like a light undertaking though. How far do you want to push it, would you want to create some form of synthesizer?