Phaser 3 can't get the start method to work right - menu

I'm trying to make a menu where the scene changes when the player clicks a button using the start method. At first, I had it all in the create function with this:
var levelOne = this.add.sprite(200, 400, 'LevelOne').setInteractive();
levelOne.on('pointerdown', function (pointer) {
this.scene.start('play');
});
But this led to an error in which it said that this.scene.start isn't a function.
I looked at a previous example where the method worked, the big difference was that the method was in the update function, so I rewrote my code to have this in the create function:
this.choice = 0;
var levelOne = this.add.sprite(200, 400, 'LevelOne').setInteractive();
levelOne.on('pointerdown', function (pointer) {
this.choice = 1;
//game.settings = {
//gameTimer: 60000
//}
});
And this in the update function:
if (this.choice == 1){
this.scene.start('play');
}
Sadly, this didn't work either and didn't even give an error message. I can't tell what went wrong. Please help.

You have to pass the scene as the context to the event function on(...) (link to the documentation), as the third parameter, so that you can access the scene properties and functions in the event callback.
levelOne.on('pointerdown', function (pointer) {
this.scene.start('play');
}, this); // <-- you have to add "this"

Related

Can i build an event object myself in Google Script App?

I bought a 3rd party google app script to use. However, it can only be called with onEdit method and their codes are private that i cannot make change. Also, what i need is based on time-trigger instead of onEdit-trigger. Thus, I tried to build my own event to trigger the function:
// This function work well and can call the 3rd Party App Script
// It is triggered by onEdit googlesheet, which works well
function funcOnEdit(e) {
3rdPartyApp.funcOnEdit(e));
}
// Below is the jsontostring result of the event e
// {authMode:"FULL",oldValue:"false",range:{columnEnd:6,columnStart:6,rowEnd:3,rowStart:3},source:{},triggerUid:"xxx",user:{email:"xxxx#gmail.com",nickname:"xxxx"},value:"TRUE"}
So I build a similar event object which triggered by time to make it happened.
function funcOnTimeTrigger(e) {
var e1 = {authMode:"FULL",oldValue:"false",range:{columnEnd:6,columnStart:6,rowEnd:3,rowStart:3},source:{},triggerUid:"xxx",user:{email:"xxxx#gmail.com",nickname:"xxxx"},value:"TRUE"};
e1.triggerUid = e.triggerUid;
3rdPartyApp.funcOnEdit(e1));
}
Unfortunately, I cannot find any document and reference code to build an "onEdit" event. Thats why, I tried find the object/class myself.
function getObjType(obj) {
var type = typeof(obj);
if (type === "object") {
try {
// Try a dummy method, catch the error
type = obj.getObjTypeXYZZY();
} catch (error) {
// Should be a TypeError - parse the object type from error message
// type = error.message.split(" object ")[1].replace('.','');
type = error.message;
}
}
return type;
}
// Below function is triggered by onEdit
function funcOnEdit_checker(e) {
getObjType(e);
}
// Unfortunately, it cannot show the object name or classname
I have no idea what to do next, may i know if it is possible to build an event class/object ourselves in Google Script App? Can anyone give some hints on how to do so? or it is not possible?
I want to create the event-obj "developers.google.com/apps-script/guides/triggers/events" manually and pass the event "e" to 3rdPartyApp.funcOnEdit function. Is it possible to do so?
Reference:
https://developers.google.com/apps-script/guides/triggers/installable
Thanks #Cooper idea, who share same thought as me.
And finally I found the result # Explain purpose of `e` event parameter in onEdit
Below is my answer (not yet optimized but work):
function funcOnTimeTrigger(e) {
var e2 = {}
e2["authMode"] = ScriptApp.AuthMode.FULL
e2['user'] = "me";
e2['range'] = SpreadsheetApp.getActive().getSheetByName("XXXXXX").getRange(5,3).activate();
e2.range.columnStart = 5;
e2.range.columnEnd = 5;
e2.range.rowStart = 3;
e2.range.rowEnd = 3;
e2['source'] = SpreadsheetApp.getActive();
e2['oldValue'] = "old";
e2['value'] = "new";
// Run The Program
3rdPartyApp.funcOnEdit(e2);
}

addTools is giving exception in rappidjs

In context of one of my assignment I was trying to use RappidJS. I was trying the below code for connecting an element by dropping it over another element.
https://resources.jointjs.com/tutorial/connecting-by-dropping
But I am getting exception as below
rappid.min.js:14 Uncaught TypeError: Cannot read property 'start' of null
at child.update (rappid.min.js:14)
at child.onRender (rappid.min.js:14)
at child.e.render (rappid.min.js:14)
at child.configure (rappid.min.js:14)
at child.addTools (rappid.min.js:14)
at child.element:pointerup (diagram.js:106)
at triggerEvents (backbone.js:338)
at triggerApi (backbone.js:322)
at eventsApi (backbone.js:110)
at child.Events.trigger (backbone.js:312)
I also took reference from below link
https://resources.jointjs.com/tutorial/link-tools .
Can any one suggest me what wrong I am doing here.
My code snippet is as below
function attachLinks(paper) {
paper.on({
'element:pointerdown': function (elementView, event) {
event.data = elementView.model.position();
},
'element:pointerup': function (elementView, event, x, y) {
var coordinates = new joint.g.Point(x, y);
var elementAbove = elementView.model;
var elementBelow = this.model.findModelsFromPoint(coordinates).find(function (el) {
return (el.id !== elementAbove.id);
});
// If the two elements are connected already, don't
// connect them again (this is application-specific though).
if (elementBelow && self.graph.getNeighbors(elementBelow).indexOf(elementAbove) === -1) {
// Move the element to the position before dragging.
elementAbove.position(event.data.x, event.data.y);
// Create a connection between elements.
var link = new joint.shapes.standard.Link();
link.source(elementAbove);
link.target(elementBelow);
link.addTo(this.model);
// Add remove button to the link.
var removeLinkTool = new joint.linkTools.Remove();
var tools = new joint.dia.ToolsView({
tools: [ removeLinkTool]
});
var linkView = link.findView(this);
linkView.addTools(tools); // getting exception at this place.
}
}
});
}
This issue is reproducible only in the paper async mode.
Make sure the view for the link is rendered when you add the link tools. For this please use joint.dia.Paper.prototype.requireView().
// It is fine to use the method in the `sync` mode as the view is rendered/updated
// synchronously as soon as the link is added to the graph.
var linkView = link.findView(paper);
// This method makes sure the view is ready to use in the `async` mode.
// It forces the view to render/update synchronously.
var linkView = paper.requireView(link);
Alternatively, you could pass async = false flag when adding the link to the graph to tell the paper to render the particular view synchronously.
link.addTo(graph, { 'async': false });

Deselection fabric.js object event

I am trying to execute some code every time a specific fabric object is "deselected". Is there any deselection event I can handle? I already have a function for when the object is selected, via the selected event, but have not found any documentation about the deselected one. At the canvas level I have the selection:cleared and selection:created events, but nothing for the deselection either.
Cheers,
Gonzalo
Use the before:selection:cleared event and get the active object or group. After that you can check if it corresponds to your specific fabric object.
canvas.on('before:selection:cleared', function() {
var clearedObject;
if(typeof(canvas.getActiveObject()) !== 'undefined') {
clearedObject = canvas.getActiveObject();
}
else {
clearedObject = canvas.getActiveGroup();
}
//do stuff with the deselected element if it is the specific one you want.
});
Just to let you all know that the newest versions of Fabric.js include a deselected event for the Object class. The only thing you need to do now is:
var aFabricObject = <create your fabric object>
aFabricObject.on('deselected', function (options) {
// your code here
});
Update for the upper answer:
The 'deselected' event fires a async method, so you can not get 'options.deselected' immediately.
var aFabricObject = <create your fabric object>
aFabricObject.on('deselected', function (options) {
console.log(options.deselected) // output undefined
setTimeout(() => {
console.log(options.deselected) // output the correct target
}, 0)
});

Variable Scope in Java Script

Arrow_onmouseover is attached with the 'onmouseover' event of an object. I get a 'timeline is not defined' JS error when the onmouseover event occurs. I know this relates to the variable scope. How can I correct this.
function startloop()
{
var changer = setInterval("changecontents();", 2000);
var timeline = setInterval("change();", 2000);
}
window.onload = startloop();
function arrow_onmouseover()
{
window.clearInterval(timeline);
window.clearInterval(changer);
}
Also what is the difference between a function called as Function(); and Function; . I believe this may also be relevant here since it greatly affects the scope of a variable.
ie what is the difference between
onclick="js();" and onclick="js;" or onclick="js"
where JS is a defined Java Script function.
Change your code like this.
var timeline,changer;
function startloop()
{
changer = setInterval("changecontents();", 2000);
timeline = setInterval("change();", 2000);
}
window.onload = startloop();
function arrow_onmouseover()
{
window.clearInterval(timeline);
window.clearInterval(changer);
}
The difference between
onclick="js();" and onclick="js;" or onclick="js"
if your js function doesn't have any parameters to receive you can simple avoid () like if you want to get the date you can call new Date(); but instead you can simply call new Date;

Propogation of *this* in nested function calls in Backbone.js

I started using backbone.js recently for a game. I used model to create Timer as follows:
var Timer = Backbone.Model.extend({
defaults: {
'hh':00, 'mm':05, 'ss':00
},
initialize: function() {
},
countDownOnce: function() {
// Count down the time by 1 sec
},
run1: function() {
this.countDownOnce();
}
run2: function() {
setInterval(this.countDownOnce, 1000);
}
});
The countDownOnce function, if called directly as in run1, works fine.
But if the function is passed as an argument to some built-in function, say setInterval as in the run2 function, the value of this is lost.
How to propagate this pointer to the built-in functions?
The Backbone docs have a useful section on binding "this".
Basically, Underscore provides a couple of very useful functions, _.bind and _.bindAll, which help you more easily manage 'this's context.
...
initialize: function() {
_.bindAll(this, 'countDownOnce' //, and whatever other functions you want bound)
}),
...
This will make sure that no matter what context it's called from, the 'this' inside countDownOnce refers to your Timer instance.
One way to do this is using call and apply. For example:
run2: function() {
setInterval(this.countDownOnce.call, 1000, this);
}
Also note that passing a closure/function reference with arguments to setTimeout() and setInterval() requires some manual hacks to work correctly in IE.
this is how javascript was designed (pun intended :)
Basically 'this' binds to the current context so if in a function/method call like this:
var Data = function(name) {
this.name = name;
}
var myData = new Data("viky");
would refer to the name element "inside" Data (i.e., myData in this case)
Now if you had the following:
var Data = function(name) {
function morphName(anotherName) {
//and if you call this like this ;)
alert(this.name); //undefined
}
}
the inner function morphName is bound to the 'current' context i.e., the outer function. In javascript everything is an object, including functions. So the outer (anonymous) function doesn't have a member called name! (makes sense?)
In order to do that most people use the following (by convention):
var Data = function(name) {
var that = this; //capture current context. Some prefer self = this;
function morphName(anotherName) {
//then you access name like that ;)
alert(that.name);
}
}
I suggest you read about javascript closures and scopes to understand this and that :D

Resources