Parsing error Unity 3D - parsing

I keep on getting this error code (UCE0001: ';' expected. Insert a semicolon at the end.), and I really just dont get why. Please help, what am I overlooking:
#pragma strict
private var vibrateTimer : float = 0.0;
function Update()
{
if (action);
{
vibrate on();
vibrateTimer = 0.25;
}
if (vibrateTimer > 0.0);
{
vibrateTimer -= Time.deltaTime;
if (vibrateTimer <= 0.0);
{
vibrate off();
}
}
}

Is this Javascript or C# or UnityScript? The using UnityEngine; says C#, the function says Javascript, the vibrate on says neither. Please clarify.
Starting from
private var vibrateTimer : float = 0.0 ();
{
//....
}
why are you wrapping the whole code in { }?
Also,
vibrate on
vibrateTimer = 0.25f;
(the first line) is not valid C# code. Also the variable declaratoin
private var vibrateTimer : float = 0.0 ();
with the () at the end seems wrong to me. But the wrapping the whole code in {} might be your first error source.

Related

Error due to invalid combination of Toast and OnSensor Changed

In this the error being displayed is mentioned below. I have searched online for the right answer none is applicable so far. I am trying to toast a simple message upon detecting a sudden change in the accelerometer readings so as to detect a fall. I don't think there is any other mistake in the code, if there is you are most welcome to rectify it.
Error: cannot find symbol method maketext(MainActivity,String,int)
This is my Code:
#Override
public void onSensorChanged(SensorEvent event) {
if (started) {
double x = event.values[0];
double y = event.values[1];
double z = event.values[2];
long timestamp = System.currentTimeMillis();
Data data = new Data(timestamp, x, y, z);
sensorData.add(data);
}
if(event.sensor.getType()==Sensor.TYPE_ACCELEROMETER){
double gacc=SensorManager.STANDARD_GRAVITY;
double a=event.values[0];
double b=event.values[1];
double c=event.values[2];
long mintime=System.currentTimeMillis();
boolean min = false;
boolean max = false;
int m = 0;
double xyz=Math.round(Math.sqrt(Math.pow(a,2)+Math.pow(b,2)+Math.pow(c,2)));
if(xyz<=3.0){
min = true;
}
if(min==true){
m++;
if(xyz>=14){
max=true;
}
}
if(min && max==true){
Toast.maketext(MainActivity.this,"FALL DETECTED!",Toast.LENGTH_LONG).show();
m=0;
min=false;
max=false;
}
if (m>4) {
m=0;
min=false;
max=false;
}
}
}
You are calling maketext instead of makeText. Note that camelCase.
Replace with:
Toast.makeText(MainActivity.this,"FALL DETECTED!",Toast.LENGTH_LONG).show();
After you correct it, make sure that you are using the android.widget.Toast.

Restrict Pan outside WMS extent in OpenLayers3

I have rectangle WMS of small area and want to restrict panning outside WMS extends, so there aren't white or black area outside the map visible at all.
Adding extent to View does not work for me and in documentation about this option is written
The extent that constrains the center, in other words, center cannot
be set outside this extent.
But as I understand this if center is in the area of extent, but on the very corner, it will show white area outside this extent, but I don't want to see white area at all.
Is it possible to achieve this with OL3?
Here's my solution. I wrote it just now, and so it is not extensively tested. It would probably break if you start rotating the map, for example, and it may be glitchy if you zoom out too far.
var constrainPan = function() {
var visible = view.calculateExtent(map.getSize());
var centre = view.getCenter();
var delta;
var adjust = false;
if ((delta = extent[0] - visible[0]) > 0) {
adjust = true;
centre[0] += delta;
} else if ((delta = extent[2] - visible[2]) < 0) {
adjust = true;
centre[0] += delta;
}
if ((delta = extent[1] - visible[1]) > 0) {
adjust = true;
centre[1] += delta;
} else if ((delta = extent[3] - visible[3]) < 0) {
adjust = true;
centre[1] += delta;
}
if (adjust) {
view.setCenter(centre);
}
};
view.on('change:resolution', constrainPan);
view.on('change:center', constrainPan);
This expects the variables map, view (with obvious meanings) and extent (the xmin, ymin, xmax, ymax you want to be visible) to be available.
Here's a more robust implementation that should work really well in any case. It's written in ES6, and requires isEqual method (from lodash or anything else ...)
const extent = [-357823.2365, 6037008.6939, 1313632.3628, 7230727.3772];
const view = this.olMap.getView();
const modifyValues = {};
// Trick to forbid panning outside extent
let constrainPan = (e) => {
const type = e.type;
const newValue = e.target.get(e.key);
const oldValue = e.oldValue;
if (isEqual(oldValue, newValue)) {
// Do nothing when event doesn't change the value
return;
}
if (isEqual(modifyValues[type], newValue)) {
// Break possible infinite loop
delete modifyValues[type];
return;
}
if (type === 'change:resolution' && newValue < oldValue) {
// Always allow zoom-in.
return;
}
const visibleExtent = view.calculateExtent(this.olMap.getSize());
const intersection = ol.extent.getIntersection(visibleExtent, extent);
const modify = !isEqual(intersection, visibleExtent);
if (modify) {
if (type === 'change:center') {
const newCenter = newValue.slice(0);
if (ol.extent.getWidth(visibleExtent) !== ol.extent.getWidth(intersection)) {
newCenter[0] = oldValue[0];
}
if (ol.extent.getHeight(visibleExtent) !== ol.extent.getHeight(intersection)) {
newCenter[1] = oldValue[1];
}
modifyValues[type] = newCenter;
view.setCenter(newCenter);
} else if (type === 'change:resolution') {
modifyValues[type] = oldValue;
view.setResolution(oldValue);
}
}
};
view.on('change:resolution', constrainPan);
view.on('change:center', constrainPan);
This is an extension to #tremby answer, but to long for a comment.
First of all, his solution works really well for me, but it was called way to often. Therefore I wrapped it in a debounce function.
So
view.on('change:resolution', constrainPan);
view.on('change:center', constrainPan);
becomes
var dConstrainPan = debounce(constrainPan);
view.on('change:resolution', dConstrainPan);
view.on('change:center', dConstrainPan);
This will result in a slight flicker, when moving outside the bounding box, bot zooming/ moving works without delay.
Still not perfect but a useful improvement from my point of view.
Debounce code:
// Returns a function, that, as long as it continues to be invoked, will not
// be triggered. The function will be called after it stops being called for
// N milliseconds. If `immediate` is passed, trigger the function on the
// leading edge, instead of the trailing.
function debounce(func, wait, immediate) {
var timeout;
return function() {
var context = this, args = arguments;
var later = function() {
timeout = null;
if (!immediate) func.apply(context, args);
};
var callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) func.apply(context, args);
};
};
Soruce: https://davidwalsh.name/javascript-debounce-function , in underscore.js

How to wait for 3 seconds in ActionScript 2 or 3?

Is there any way to implement waiting for, say, 3 seconds in ActionScript, but to stay within same function? I have looked setInterval, setTimeOut and similar functions, but what I really need is this:
public function foo(param1, param2, param3) {
//do something here
//wait for 3 seconds
//3 seconds have passed, now do something more
}
In case you wonder why I need this - it is a legal requirement, and no, I can't change it.
Use the Timer to call a function after 3 seconds.
var timer:Timer = new Timer(3000);
timer.addEventListener(TimerEvent.TIMER, callback); // will call callback()
timer.start();
To do this properly, you should create the timer as an instance variable so you can remove the listener and the timer instance when the function is called, to avoid leaks.
class Test {
private var timer:Timer = new Timer(3000);
public function foo(param1:int, param2:int, param3:int):void {
// do something here
timer.addEventListener(TimerEvent.TIMER, fooPartTwo);
timer.start();
}
private function fooPartTwo(event:TimerEvent):void {
timer.removeEventListener(TimerEvent.TIMER, fooPartTwo);
timer = null;
// 3 seconds have passed, now do something more
}
}
You could also use another function inside your foo function and retain scope, so you don't need to pass variables around.
function foo(param1:int, param2:int, param3:int):void {
var x:int = 2; // you can use variables as you would normally
// do something here
var timer:Timer = new Timer(3000);
var afterWaiting:Function = function(event:TimerEvent):void {
timer.removeEventListener(TimerEvent.TIMER, afterWaiting);
timer = null;
// 3 seconds have passed, now do something more
// the scope is retained and you can still refer to the variables you
// used earlier
x += 2;
}
timer.addEventListener(TimerEvent.TIMER, afterWaiting);
timer.start();
}
For AS3 use Radu's answer.
For AS2 use the setInterval function like so:
var timer = setInterval(function, 3000, param1, param2);
function (param1, param2) {
// your function here
clearInterval(timer);
}
You can also use delayedCall, from TweenMax. IMHO, it's the sharpest way to do that if you are familiar to TweenMax family.
TweenMax.delayedCall(1, myFunction, ["param1", 2]);
function myFunction(param1:String, param2:Number):void
{
trace("called myFunction and passed params: " + param1 + ", " + param2);
}
In your case, using a anonymous function:
public function foo(param1, param2, param3) {
//do something here
trace("I gonna wait 3 seconds");
TweenMax.delayedCall(3, function()
{
trace("3 seconds have passed");
});
}
why you are doing some confused ways instead of doing the right way?
there is a method named:"setTimeout()";
setTimeout(myFunction,3000);
myFunction is the function you want to call after the period.and 3000 is the period you want to wait(as miliseconds).
you don't need to set then clear interval, or make a timer with one repeat count or do sth else with more trouble☺.
There is no Sleep in ActionScript. But there are other ways to achieve the same thing without having all your code in a single function and wait within that function a specific amount of time.
You can easily have your code in two functions and call the 2nd one after a specific timeout you set in your 1st function.
THIS IS NOT WITHIN ONE FUNCTION - ANSWERS: "How to wait for X seconds in AS2 & 3"
...without using setInterval or clearInterval.
The answers posted above are much faster and easier to use. I posted this here, just in case...
Sometimes you may not be able to use set/clearInterval or other methods based on development restrictions. Here is a way to make a delay happen without using those methods.
AS2 - If you copy/paste the code below to your timeline, make sure to add two movie clips to the stage, btnTest and btnGlowTest (include like instance names). Make "btnGlowTest" larger, a different color, & behind "btnTest" (to simulate a glow and a button, respectively).
Compile and check the output panel for the trace statements to see how the code is working. Click on btnTest - btnGlowTest will then become visible throughout the duration of the delay, (just for visual representation).
I have an onEnterFrame countdown timer in here as well, (demos stopping/switching timers).
If you want the delay/glow to be longer - increase the glowGameTime number. Change the names to fit your own needs and/or apply the logic differently.
var startTime:Number = 0;
var currentTime:Number = 0;
var mainTime:Number = 5;//"game" time on enter frame
var glowStartTime:Number = 0;
var glowCurrentTime:Number = 0;
var glowGameTime:Number = 1.8;//"delayed" time on press
btnGlowTest._visible = false;
this.onEnterFrame = TimerFunction;
startTime = getTimer();
function TimerFunction()
{
currentTime = getTimer();
var timeLeft:Number = mainTime - ((currentTime - startTime)/1000);
timeLeft = Math.floor(timeLeft);
trace("timeLeft = " + timeLeft);
if(timeLeft <= 0)
{
trace("time's up...3 bucks off");
//...do stuff here
btnGlowTest._visible = false;//just for show
btnTest._visible = false;//just for show
StopTime();
}
}
function glowTimerFunction()
{
glowCurrentTime = getTimer();
var glowTimeLeft:Number = glowGameTime - ((glowCurrentTime - glowStartTime)/1000);
glowTimeLeft = Math.floor(glowTimeLeft);
//trace("glowTimeleft = " + glowTimeLeft);
if(glowTimeLeft <= 0)
{
trace("TIME DELAY COMPLETE!");
//...do stuff here
btnGlowTest._visible = false;//just for show
btnTest._visible = false;//just for show
StopTime();
}
}
btnTest.onPress = function()
{
trace("onPress");
btnGlowTest._visible = true;
StopTime();
GlowTime();
}
function GlowTime()
{
trace("GlowTime Function");
this.onEnterFrame = glowTimerFunction;
glowStartTime = getTimer();
}
function StopTime()
{
trace(">>--StopTime--<<");
delete this.onEnterFrame;
}
AS3 - Below is the code from above setup to run in AS3. There are different ways to accomplish similar results, yet based on the project scope, these are the methods that were used in order to get things functioning properly.
If you copy/paste the code below to your timeline, make sure to add two movie clips to the stage, btnTest and btnGlowTest (include like instance names). Make "btnGlowTest" larger, a different color, & behind "btnTest" (to simulate a glow and a button, respectively).
Compile and check the output panel for the trace statements to see how the code is working. Click on btnTest - btnGlowTest will then become visible throughout the duration of the delay, (just for visual representation).
If you want the delay/glow to be longer - increase the GlowTimer:Timer number, (currently set to 950). Change the names to fit your own needs and/or apply the logic differently.
import flash.events.MouseEvent;
import flash.utils.Timer;
import flash.events.TimerEvent;
var startTime:Number = 0;
var currentTime:Number = 0;
var gameTime:Number = 4;//"game" time on enter frame
var GlowTimer:Timer = new Timer(950,0);//"delayed" time on press
btnGlowTest.visible = false;
GlowTimer.addEventListener(TimerEvent.TIMER, GlowTimeListener, false, 0, true);
btnTest.addEventListener(MouseEvent.MOUSE_DOWN, btnTestPressed, false, 0, true);
addEventListener(Event.ENTER_FRAME,TimerFunction, false, 0, true);
startTime = getTimer();
function TimerFunction(event:Event)
{
currentTime = getTimer();
var timeLeft:Number = gameTime - ((currentTime - startTime)/1000);
timeLeft = Math.floor(timeLeft);
trace("timeLeft = " + timeLeft);
if(timeLeft <= 0)
{
trace("time's up, 3 bucks off");
StopTime();
}
}
function GlowTimeListener (e:TimerEvent):void
{
trace("TIME DELAY COMPLETE!");
StopTime();
}
function btnTestPressed(e:MouseEvent)
{
trace("PRESSED");
removeEventListener(Event.ENTER_FRAME, TimerFunction);
btnGlowTest.visible = true;
GlowTimer.start();
}
function StopTime()
{
trace(">>--Stop Time--<<");
btnGlowTest.visible = false;//just for show
btnTest.visible = false;//just for show
GlowTimer.stop();
removeEventListener(TimerEvent.TIMER, GlowTimeListener);
removeEventListener(Event.ENTER_FRAME, TimerFunction);
}

AS3 time that needs to pause

I'm working on a mobile game and need the game clock to pause when the game loses focus, for example when call comes in. I have everything working except that when the game gains focus again the time adjusts to as if it had been running the whole time. If someone is on a 3 minute call when they get back they should find the game time where it was.
Here is my code:
public function showTime(event:Event){
gameTime = getTimer()-gameStartTime;
timeDisplay.text = "Time: "+clockTime(gameTime);
}
public function clockTime(ms:int) {
var seconds:int = Math.floor(ms/1000);
var minutes:int = Math.floor(seconds/60);
seconds -= minutes*60;
var timeString:String = minutes+":"+String(seconds+100).substr(1,2);
return timeString;
}
public function onActivate(event:Event):void {
addEventListener(Event.ENTER_FRAME, showTime);
}
public function onDeactivate(event:Event):void {
removeEventListener(Event.ENTER_FRAME, showTime);
}
I've been Googling this for two days and am stuck. Could someone please point me in the right direction? Some sample code would be a benefit too since I'm pretty new to AS3. Thanks!
Rich
You can check out this Stopwatch tutorial that I wrote a while back:
http://www.popamihai.com/2010/10/flex/using-the-timer-class-in-flex-to-display-a-simple-stopwatch/
It is written with Flex Builder 3 but you could easily copy/paste the code. Example with view source enabled is also included
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="vertical" verticalAlign="middle"
backgroundColor="white" viewSourceURL="srcview/index.html" creationComplete="init()">
<mx:Script>
<![CDATA[
import flash.utils.getTimer;
import flash.utils.Timer;
import flash.events.TimerEvent;
private const TIMER_INTERVAL:int = 50;
private var timerAtStart:Number = 0;
private var timerAtPause:Number = 0;
private var t:Timer;
private var d:Date;
[Bindable] private var sec:int = 0;
[Bindable] private var min:int = 0;
[Bindable] private var mls:int = 0;
private function init():void {
t = new Timer(TIMER_INTERVAL);
t.addEventListener( TimerEvent.TIMER, updateTimer );
}
private function updateTimer( evt:TimerEvent ):void{
d = new Date( getTimer() - timerAtStart + timerAtPause);
min = d.minutes;
sec = d.seconds;
mls = d.milliseconds;
}
private function startPauseTimer( event:MouseEvent ):void{
if ( event.target.label == "start" ) {
event.target.label = "pause";
timerAtStart = getTimer();
t.start();
} else {
event.target.label = "start";
timerAtPause = min * 60000 + sec * 1000 + mls;
t.stop();
}
}
]]>
</mx:Script>
<mx:Label text="{min + ' : ' + sec + ' : ' + mls}" fontSize="16" fontWeight="bold"/>
<mx:HBox>
<mx:Button label="start" click="startPauseTimer( event )"/>
</mx:HBox>
</mx:Application>
You're calculating your time based on the current time - gameStartTime. You either need to take the delay into account (calculate the total time stopped by using getTimer() in the onActivate() and onDeactivate() functions, then add that difference to gameStartTime), or if you don't want to change gameStartTime, then you calcuate your time based on delta time. Something like:
private var m_prevTime:int = 0;
public function startGame():void
{
// set the prevTime only when you start the game, otherwise you'll
// take into account all the time for flash to get going, your init,
// opening screens etc
this.m_prevTime = getTimer();
}
public function showTime(event:Event)
{
// get the difference in time
var currTime:int = getTimer();
gameTime += currTime - this.m_prevTime // currTime - prevTime = delta time
this.m_prevTime = currTime; // hold the current time
// display it
timeDisplay.text = "Time: "+clockTime(gameTime);
}
public function onActivate(event:Event):void
{
// we're reactivating, so make sure prev time is updated
this.m_prevTime = getTimer();
addEventListener(Event.ENTER_FRAME, showTime);
}
You'll miss out on a frame's time when coming back from the update, but it's not noticable (or you can subtract a frame's time in the onActivate() function)
Instead of using getTimer(), you should create a timer object and add an event listener to "tick" to update the clock. You can even set it to tick once per second so you don't have to convert the MS.
public function onActivate(event:Event):void {
myTimer.start();
}
public function onDeactivate(event:Event):void {
myTimer.stop();
}
See the timer reference: http://www.adobe.com/livedocs/flash/9.0/ActionScriptLangRefV3/flash/utils/Timer.html

Errors in Action Script 3 in streaming .mp3 player

I'm trying to build a streaming .mp3 player to run various sound files on my web site. To do that, I followed a tutorial that includes a code template at:
http://blog.0tutor.com/post.aspx?id=202&title=Mp3%20player%20with%20volume%20slider%20using%20Actionscript%203
However, whether I preserve the template's direction to the author's own sound file or insert my own direction to my online sound file, I keep on running into glitches in the ActionScript that I can't fathom.
Those errors are:
1084: Syntax error: expecting rightparen before _.
1086: Syntax error: expecting semicolon before rightparen.
When I try to correct them, I get new errors. I can't determine whether the sound file is loading; it certainly never plays. The volume slider does not work.
I did find one line that looked like it should have been commented out, the one that reads
to start at the same place
So I tried commenting that out. No dice. Same errors.
Thanks in advance for any suggestions. Code follows:
var musicPiece:Sound = new Sound(new URLRequest _
("http://blog.0tutor.com/JeffWofford_Trouble.mp3"));
var mySoundChannel:SoundChannel;
var isPlaying:Boolean = false;
to start at the same place
var pos:Number = 0;
play_btn.addEventListener(MouseEvent.CLICK, play_);
function play_(event:Event):void {
if (!isPlaying) {
mySoundChannel = musicPiece.play(pos);
isPlaying = true;
}
}
pause_btn.addEventListener(MouseEvent.CLICK, pause_);
function pause_(event:Event):void {
if (isPlaying) {
pos = mySoundChannel.position;
mySoundChannel.stop();
isPlaying = false;
}
}
stop_btn.addEventListener(MouseEvent.CLICK, stop_);
function stop_(event:Event):void {
if (mySoundChannel != null) {
mySoundChannel.stop();
pos = 0;
isPlaying = false;
}
}
var rectangle:Rectangle = new Rectangle(0,0,100,0);
var dragging:Boolean = false;
volume_mc.mySlider_mc.addEventListener(MouseEvent.MOUSE_DOWN, startDragging);
function startDragging(event:Event):void {
volume_mc.mySlider_mc.startDrag(false,rectangle);
dragging = true;
volume_mc.mySlider_mc.addEventListener(Event.ENTER_FRAME, adjustVolume);
}
function adjustVolume(event:Event):void {
var myVol:Number = volume_mc.mySlider_mc.x / 100;
var mySoundTransform:SoundTransform = new SoundTransform(myVol);
if (mySoundChannel != null) {
mySoundChannel.soundTransform = mySoundTransform;
}
}
stage.addEventListener(MouseEvent.MOUSE_UP, stopDragging);
function stopDragging(event:Event):void {
if (dragging) {
dragging = false;
volume_mc.mySlider_mc.stopDrag();
}
}
Syntax errors are just what it says they are, the code is not properly written. For instance , you shouldn't have an underscore after URLREquest
var musicPiece:Sound =
new Sound(new URLRequest("http://blog.0tutor.com/JeffWofford_Trouble.mp3"));
to start at the same place should be commented out, simply because it's a comment, it's not a variable or a function.
to call a function "play_" is not really good practice either. Call it soundPlay, if you're concern about conflicts.
same comment for pause_ and stop_

Resources