I have guiTexts called scoreLevel1, scoreLevel2 where i want to show the score from the right levels but it isn't showing any text or scores... There are no build errors. How do I make it show up as expected?
var Score : int;
function Update () {
Score -= 1 * Time.deltaTime;
guiText.text = "Score: "+Score;
TimerOfDeath();
}
HighScores.js:
//run at start if score doesn't exist yet to initialise playerPref
function Start(){
if(!PlayerPrefs.HasKey(Application.loadedLevelName+"HighScore"))
PlayerPrefs.SetFloat(Application.loadedLevelName+"HighScore", 0);
}
//run when level is completed
function OnTriggerEnter(other : Collider){
if(other.tag == "Player"){
Score = gameObject.Find("ScoreCount").GetComponent("ScoringPts").Update("Score");
if(Score > PlayerPrefs.GetFloat(Application.loadedLevelName+"HighScore"))
{
PlayerPrefs.SetFloat(Application.loadedLevelName+"HighScore", Score);
}
}
}
GetHighScores.js:
#pragma strict
function Start () {
var hscount = 1;
var iterations = 1;
var maxIterations = 5;
var findtext = gameObject.Find("scoreLevel"+(hscount));
while(hscount < 5 && iterations < maxIterations){
if(!PlayerPrefs.HasKey("Level"+(hscount)+"HighScore")){
findtext.guiText.text = "Level"+(hscount)+ ": " + PlayerPrefs.GetFloat("Level"+(hscount)+"HighScore");
hscount++;
}
iterations++;
}
}
Related
The default audio sample rate is 48000. Is it possible to change it to other values like 44100?
I log the value of AudioSettings.outputSampleRate and it shows 48000. But it doesn't seem possible to change that value.
Here is the code to change sample rate of Unity's AudioClip:
Most simple, but very rough
Averaging approach, but channels are get mixed
Averaging approach for each channel (best quality)
public static AudioClip SetSampleRateSimple(AudioClip clip, int frequency)
{
if (clip.frequency == frequency) return clip;
var samples = new float[clip.samples * clip.channels];
clip.GetData(samples, 0);
var samplesLength = (int)(frequency * clip.length) * clip.channels;
var samplesNew = new float[samplesLength];
var clipNew = AudioClip.Create(clip.name + "_" + frequency, samplesLength, clip.channels, frequency, false);
for (var i = 0; i < samplesLength; i++)
{
var index = (int) ((float) i * samples.Length / samplesLength);
samplesNew[i] = samples[index];
}
clipNew.SetData(samplesNew, 0);
return clipNew;
}
public static AudioClip SetSampleRateAverage(AudioClip clip, int frequency)
{
if (clip.frequency == frequency) return clip;
var samples = new float[clip.samples * clip.channels];
clip.GetData(samples, 0);
var samplesNewLength = (int) (frequency * clip.length) * clip.channels;
var samplesNew = new float[samplesNewLength];
var clipNew = AudioClip.Create(clip.name + "_" + frequency, samplesNewLength, clip.channels, frequency, false);
var index = 0;
var sum = 0f;
var count = 0;
for (var i = 0; i < samples.Length; i++)
{
var index_ = (int)((float)i / samples.Length * samplesNewLength);
if (index_ == index)
{
sum += samples[i];
count++;
}
else
{
samplesNew[index] = sum / count;
index = index_;
sum = samples[i];
count = 1;
}
}
clipNew.SetData(samplesNew, 0);
return clipNew;
}
public static AudioClip SetSampleRate(AudioClip clip, int frequency)
{
if (clip.frequency == frequency) return clip;
if (clip.channels != 1 && clip.channels != 2) return clip;
var samples = new float[clip.samples * clip.channels];
clip.GetData(samples, 0);
var samplesNewLength = (int) (frequency * clip.length) * clip.channels;
var clipNew = AudioClip.Create(clip.name + "_" + frequency, samplesNewLength, clip.channels, frequency, false);
var channelsOriginal = new List<float[]>();
var channelsNew = new List<float[]>();
if (clip.channels == 1)
{
channelsOriginal.Add(samples);
channelsNew.Add(new float[(int) (frequency * clip.length)]);
}
else
{
channelsOriginal.Add(new float[clip.samples]);
channelsOriginal.Add(new float[clip.samples]);
channelsNew.Add(new float[(int) (frequency * clip.length)]);
channelsNew.Add(new float[(int) (frequency * clip.length)]);
for (var i = 0; i < samples.Length; i++)
{
channelsOriginal[i % 2][i / 2] = samples[i];
}
}
for (var c = 0; c < clip.channels; c++)
{
var index = 0;
var sum = 0f;
var count = 0;
var channelSamples = channelsOriginal[c];
for (var i = 0; i < channelSamples.Length; i++)
{
var index_ = (int) ((float) i / channelSamples.Length * channelsNew[c].Length);
if (index_ == index)
{
sum += channelSamples[i];
count++;
}
else
{
channelsNew[c][index] = sum / count;
index = index_;
sum = channelSamples[i];
count = 1;
}
}
}
float[] samplesNew;
if (clip.channels == 1)
{
samplesNew = channelsNew[0];
}
else
{
samplesNew = new float[channelsNew[0].Length + channelsNew[1].Length];
for (var i = 0; i < samplesNew.Length; i++)
{
samplesNew[i] = channelsNew[i % 2][i / 2];
}
}
clipNew.SetData(samplesNew, 0);
return clipNew;
}
I'm trying to convert this javascript password score function to swift, so I can use the same logic on mobile as we do on web. Here is the JS fiddle with the code to test:
function scorePassword(pass) {
var score = 0;
if (!pass)
return score;
// award every unique letter until 5 repetitions
var letters = new Object();
for (var i=0; i<pass.length; i++) {
letters[pass[i]] = (letters[pass[i]] || 0) + 1;
score += 5.0 / letters[pass[i]];
}
// bonus points for mixing it up
var variations = {
digits: /\d/.test(pass),
lower: /[a-z]/.test(pass),
upper: /[A-Z]/.test(pass),
nonWords: /\W/.test(pass),
}
variationCount = 0;
for (var check in variations) {
variationCount += (variations[check] == true) ? 1 : 0;
}
score += (variationCount - 1) * 10;
return parseInt(score);
}
function checkPassStrength(pass) {
var score = scorePassword(pass);
if (score > 80)
return "Strong";
if (score > 60)
return "Good";
if (score >= 30)
return "Weak";
return "";
}
I'm having an issue in converting this part:
var letters = new Object();
for (var i=0; i<pass.length; i++) {
letters[pass[i]] = (letters[pass[i]] || 0) + 1;
score += 5.0 / letters[pass[i]];
}
I've tried to create a dictionary to store the character as key and then increment the value with each occurrences of that key, but it's not working as expected.
let string = "Testing22!"
var score = 0
var dictionary = [String.Element: Int]()
for x in string {
let value = dictionary[x] ?? 0
dictionary[x] = value + 1
score += 5 / value
}
print(dictionary) //["s": 1, "T": 1, "g": 1, "2": 2, "n": 1, "i": 1, "!": 1, "t": 1, "e": 1]
print(score)
I'm also not sure of the most efficient way to handle the regex checks for the bonus points section.
I'd port it over to swift like this, I'm sure there are some improvements to be made, but thats a quick conversion:
func scorePassword(_ inputString: String?) -> Double {
var score: Double = 0
guard let string = inputString, !string.isEmpty else { return score }
// award every unique letter until 5 repetitions
let countedSet = NSCountedSet()
for x in string {
countedSet.add(x)
score += 5.0 / Double(countedSet.count(for: x))
}
// bonus points for mixing it up
let variations = [
"^(?=.*[0-9]).*$",
"^(?=.*[a-z]).*$",
"^(?=.*[A-Z]).*$",
"^(?=.*\\W).*$"
]
var variationCount: Double = 0
for check in variations {
print(string.testRegex(check))
variationCount += string.testRegex(check) ? 1 : 0
}
score += (variationCount - 1) * 10
return floor(score)
}
func checkPassStrength(_ inputString: String?) -> String {
let score = scorePassword(inputString)
if score > 80 {
return "Strong"
} else if score > 60 {
return "Good"
} else if score > 30 {
return "Weak"
}
return ""
}
extension String {
func testRegex(_ regex: String) -> Bool {
let test = NSPredicate(format: "SELF MATCHES %#", regex)
return test.evaluate(with: self)
}
}
You can run js code inside Swift and get the result from it, so you can share code between platforms.
let jsSource = """
function scorePassword(pass) {
var score = 0;
if (!pass)
return score;
// award every unique letter until 5 repetitions
var letters = new Object();
for (var i=0; i<pass.length; i++) {
letters[pass[i]] = (letters[pass[i]] || 0) + 1;
score += 5.0 / letters[pass[i]];
}
// bonus points for mixing it up
var variations = {
digits: /d/.test(pass),
lower: /[a-z]/.test(pass),
upper: /[A-Z]/.test(pass),
nonWords: /W/.test(pass),
}
variationCount = 0;
for (var check in variations) {
variationCount += (variations[check] == true) ? 1 : 0;
}
score += (variationCount - 1) * 10;
return parseInt(score);
}
function checkPassStrength(pass) {
var score = scorePassword(pass);
if (score > 80)
return "Strong";
if (score > 60)
return "Good";
if (score >= 30)
return "Weak";
return "";
}
"""
let context = JSContext()
context?.evaluateScript(jsSource)
let testFunction = context?.objectForKeyedSubscript("scorePassword")
let result = testFunction?.call(withArguments: ["1234"])
print("js result : " , result )
Note; I edited the part "digits: /\d/.test(pass)" to "digits: /d/.test(pass)"
I'm develop a pulse counter(coin counter) in raspberry pi with windows 10 iot core, and i need to count pulses that have a interval time of 25 miliseconds like this:
0,05€ - 1 pulse
0,10€ - 2 pulses
0,20€ - 4 pulses
0,50€ - 10 pulses
1€ - 20 pulses
2€ - 40 pulses
like this image: pulses
I need to print the number of pulses(to have the value inserted) when the interval time is diferent of 25 miliseconds.
I have this code:
public MainPage()
{
this.InitializeComponent();
InitGPIO();
}
private void InitGPIO()
{
var gpio = GpioController.GetDefault();
if (gpio == null)
{
GpioStatus.Text = "There is no GPIO controller on this device.";
}
coinPin = gpio.OpenPin(coin_Pin);
if (coinPin.IsDriveModeSupported(GpioPinDriveMode.InputPullUp))
{
coinPin.SetDriveMode(GpioPinDriveMode.InputPullUp);
} else
{
coinPin.SetDriveMode(GpioPinDriveMode.Input);
}
coinPin.DebounceTimeout = TimeSpan.FromMilliseconds(25);
coinPin.ValueChanged += coinPin_ValueChanged;
GpioStatus.Text = "GPIO pins initialized correctly.";
}
private void coinPin_ValueChanged(GpioPin sender, GpioPinValueChangedEventArgs e)
{
if (e.Edge == GpioPinEdge.FallingEdge)
{
counter++;
}
var task = Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
if (e.Edge == GpioPinEdge.FallingEdge)
{
//counter++;
var time = PulseIn(coinPin, e.Edge);
value = (counter * 5);
value100 = value / 100;
//money.Text = "Eur: " + (decimal)value100 + " €";
if (time != 25)
{
money.Text = "Eur: " + (decimal)value100 + " €";
GpioStatus.Text = "" + time;
} else
{
GpioStatus.IsEnabled = false;
}
//GpioStatus.Text = "" + time + "";
} else
{
///GpioStatus.Text = "" + coinPin.DebounceTimeout;
}
});
}
private double PulseIn(GpioPin pin, GpioPinEdge edge)
{
var sw = new Stopwatch();
while (edge.Equals(GpioPinEdge.RisingEdge))
{
//sw.Start();
}
sw.Start();
if (!edge.Equals(GpioPinEdge.RisingEdge))
{
//sw.Stop();
}
sw.Stop();
return sw.Elapsed.TotalMilliseconds;
}
private const int coin_Pin = 24;
private int counter = 0;
private double value = 0;
private double value100 = 0;
private GpioPin coinPin;
Can you help me please?
Thank you very much.
From your code,
sw.Start();
if (!edge.Equals(GpioPinEdge.RisingEdge))
{
//sw.Stop();
}
sw.Stop();
it actually measures the execute time of the if statement that between sw.Start() and sw.Stop(). This does not make sense. Record the watch.Elapsed.TotalMilliseconds when the falling edge arrived and restart the stopwatch to measure the pulse interval time. To do this, I add the following two code lines under counter++, remove var time = PulseIn(coinPin, e.Edge) and use timeinterval in GpioStatus.Text = "" + timeinterval instead.
timeinterval = watch.Elapsed.TotalMilliseconds;
watch.Restart();
The following is complete code piece:
private Stopwatch watch = new Stopwatch();
private void coinPin_ValueChanged(GpioPin sender, GpioPinValueChangedEventArgs e)
{
double timeinterval = 0;
if (e.Edge == GpioPinEdge.FallingEdge)
{
counter++;
timeinterval = watch.Elapsed.TotalMilliseconds;
watch.Restart();
}
var task = Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
if (e.Edge == GpioPinEdge.FallingEdge)
{
//var time = PulseIn(coinPin, e.Edge);
value = (counter * 5);
value100 = value / 100;
if (timeinterval != 25)
{
money.Text = "Eur: " + (decimal)value100 + " €";
GpioStatus.Text = "" + timeinterval;
}
//...
}
});
}
You can try above code piece to see if it meets your accuracy requirement.
Note: It is not suitable to measure hardware pulse interval in software level because the software jitter is always unpredictable.
I'm making a DragDrop class on as3. I'm trying to make movable movie clips "stick" to a target MovieClip. I've got the basic drag drop and positioning/sticking to work but when I try to create an "easing" effect using Enter Frame, somehow the movie clips move to 0 x and y position.
Here's the code that's working (without EnterFrame Event).
package {
public class DragDrop {
public var clip:MovieClip;
public var targ:MovieClip;
public var myHomeX:Number;
public var myHomeY:Number;
public var myFinalX:Number;
public var myFinalY:Number;
public function selectClip(clipV:MovieClip,targV:MovieClip):void {
clip = clipV;
targ = targV;
var myHomeX = clip.x;
var myHomeY = clip.y;
var myFinalX = targ.x;
var myFinalY = targ.y;
clip.addEventListener(MouseEvent.MOUSE_DOWN,startDragging);
clip.addEventListener(MouseEvent.MOUSE_UP,stopDragging);
clip.addEventListener(MouseEvent.ROLL_OVER,rollOver);
clip.addEventListener(MouseEvent.ROLL_OUT,rollOut);
function startDragging(e:MouseEvent):void {
clip.startDrag();
clip.beingDragged = true;
clip.parent.setChildIndex(clip,clip.parent.numChildren - 1);
}
function stopDragging(e:MouseEvent):void {
clip.stopDrag();
clip.beingDragged = false;
var onTarget:MovieClip;
if (clip.dropTarget != null)
{
onTarget = e.target.dropTarget.parent;
}
else
{
onTarget = null;
}
if ((onTarget == targ))
{
clip.onTarget = true;
targ.gotoAndStop(2);
clip.x = myFinalX;
clip.y = myFinalY;
}
else
{
clip.onTarget = false;
targ.gotoAndStop(1);
clip.x = myHomeX;
clip.y = myHomeY;
}
}
function rollOver(e:MouseEvent) {
clipGlow.restart();
}
function rollOut(e:MouseEvent) {
clipGlow.reverse();
}
}
}
}
Here's the code that's not working (with EnterFrame Event).
package {
public class DragDrop {
public var clip:MovieClip;
public var targ:MovieClip;
public var clip:MovieClip;
public var targ:MovieClip;
public var myHomeX:Number;
public var myHomeY:Number;
public var myFinalX:Number;
public var myFinalY:Number;
public function selectClip(clipV:MovieClip,targV:MovieClip):void {
clip = clipV;
targ = targV;
var myHomeX = clip.x;
var myHomeY = clip.y;
var myFinalX = targ.x;
var myFinalY = targ.y;
clip.addEventListener(MouseEvent.MOUSE_DOWN,startDragging);
clip.addEventListener(MouseEvent.MOUSE_UP,stopDragging);
clip.addEventListener(MouseEvent.ROLL_OVER,rollOver);
clip.addEventListener(MouseEvent.ROLL_OUT,rollOut);
clip.addEventListener(Event.ENTER_FRAME,slide);
function startDragging(e:MouseEvent):void {
clip.startDrag();
clip.beingDragged = true;
clip.parent.setChildIndex(clip,clip.parent.numChildren - 1);
}
function stopDragging(e:MouseEvent):void {
clip.stopDrag();
clip.beingDragged = false;
var onTarget:MovieClip;
if (clip.dropTarget != null)
{
onTarget = e.target.dropTarget.parent;
}
else
{
onTarget = null;
}
if ((onTarget == targ))
{
clip.onTarget = true;
targ.gotoAndStop(2);
}
else
{
clip.onTarget = false;
targ.gotoAndStop(1);
}
}
function rollOver(e:MouseEvent) {
clipGlow.restart();
}
function rollOut(e:MouseEvent) {
clipGlow.reverse();
}
function slide(e:Event):void {
if (! clip.beingDragged && ! clip.onTarget)
{
clip.x -= clip.x - clip.myHomeX / 5;
clip.y -= clip.y - clip.myHomeY / 5;
clip.scaleX += (1 - clip.scaleX) / 5;
clip.scaleY += (1 - clip.scaleY) / 5;
}
else if (! clip.beingDragged && clip.onTarget)
{
clip.x -= clip.x - clip.myFinalX / 5;
clip.y -= clip.y - clip.myFinalY / 5;
clip.scaleX += (1.5 - clip.scaleX) / 5;
clip.scaleY += (1.5 - clip.scaleY) / 5;
}
}
}
}
}
Thanks in advance for any help. :)
If you do this:
var myHomeX = clip.x;
var myHomeY = clip.y;
var myFinalX = targ.x;
var myFinalY = targ.y;
Then maybe clip.myHomeX should be myHomeX only etc?
function slide(e:Event):void {
if (! clip.beingDragged && ! clip.onTarget)
{
clip.x -= clip.x -myHomeX / 5;
clip.y -= clip.y -myHomeY / 5;
clip.scaleX += (1 - clip.scaleX) / 5;
clip.scaleY += (1 - clip.scaleY) / 5;
}
else if (! clip.beingDragged && clip.onTarget)
{
clip.x -= clip.x -myFinalX / 5;
clip.y -= clip.y -myFinalY / 5;
clip.scaleX += (1.5 - clip.scaleX) / 5;
clip.scaleY += (1.5 - clip.scaleY) / 5;
}
}
#pragma strict
var challenge1 : Texture;
var challenge2 : Texture;
var challenge3 : Texture;
var LevelOneEnabled = true;
var LevelTwoEnabled = false;
var LevelThreeEnabled = false;
var Score : TextMesh;
var Score2 : TextMesh;
var Score3 : TextMesh;
function Start(){
}
function Awake(){
Score.text = "Highscore: "+ PlayerPrefs.GetInt("JeepneyScore");
Score2.text = "Highscore: "+ PlayerPrefs.GetInt("JeepneyScore2");
Score3.text = "Best Time: "+ PlayerPrefs.GetFloat("JeepneyScore3");
}
function OnGUI()
{
GUI.enabled = LevelOneEnabled;
if(GUI.Button(Rect(400,100,250,250),challenge1)){
Application.LoadLevel("LoadScene");
}
GUI.enabled = LevelTwoEnabled;
if(GUI.Button(Rect(700,100,250,250),challenge2)){
Application.LoadLevel("LoadScene2");
}
GUI.enabled = LevelThreeEnabled;
if(GUI.Button(Rect(1000,100,250,250),challenge3)){
Application.LoadLevel("LoadScene3");
}
}
Can anybody knows hot to get the logic in playerprefs so that the LoadScene2, and 3
will unlock after finishing the first mission?
Please I'm hoping for an answer :(
put in
var level : int;
then in start
level = PlayerPrefs.GetInt("level",0);
then in your if(GUI.Buttons){}
if(level >= 2){}
and
if(level >= 3){}
and so on and in your actual levels set the int in your playerprefs once they complete the level, probably load the int again and use if to check if it is greater than then replace if it is not
EDIT:
var levelnum : int = 2;
PlayerPrefs.SetInt("level",levelnum);